1

I am doing some POSTing to my laravel API. I have added a unique 'api_token' column to the users table, and I want to retrieve the user from this token.

In a controller I can validate a token - the $apiUserValid is true or false depending on whether or not a row exists with a matching api_token value:

$apiToken = "Y2uibY5MIV";//correct token
$apiCredentials = ['api_token' => $apiToken];
$apiUserValid = \Auth::guard('api')->validate($apiCredentials);
if ($apiUserValid) {
    var_dump(\Illuminate\Support\Facades\Auth::user()); // shows "NULL"
    var_dump(\Illuminate\Support\Facades\Auth::id()); //shows NULL
    var_dump(\Illuminate\Support\Facades\Auth::guard('api')->user()); // shows "NULL"
    die();
} else {
    die('not valid');// when the token is incorrect this branch is taken
}

However, I want to get the userId of the user with that token.

The SessionGuard has some methods that look relevant - such as login() but these are not present in the TokenGuard.

I am currently simulating this in a controller rather than dealing with a http request object - this could be part of my problem.

How do I get the user id of the person making the POST?

1 Answer 1

1

You can use this:

<?php

use Illuminate\Support\Facades\Auth;

$userId = Auth::id();

The relevant documentation is here.

Alternatively, you can use this:

<?php

use App\User;

$user = User::where('api_token', $apiToken)->first();

$userId = $user->id;
Sign up to request clarification or add additional context in comments.

4 Comments

That does not work for me - even though validate() returns true, it does not set the user object as I hoped. If I add var_dump(\Illuminate\Support\Facades\Auth::id()) after I do the \Auth::guard('api')->validate($apiCredentials); it shows id() is null.
Thanks, that works (with $user = User::where('api_token', $apiToken)->first();) Does not seem ideal,I would have liked to have used native methods in laravel's authentication classes but I can run with that
Try this: Auth::guard('api')->user()
as I say in my question - \Auth::guard('api')->user()); // shows "NULL"

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.