NULL pointer
NULL pointer

Reputation: 1377

Laravel api authentication - how do I get User by api_token

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?

Upvotes: 1

Views: 6123

Answers (1)

bfl
bfl

Reputation: 403

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;

Upvotes: 1

Related Questions