STWilson
STWilson

Reputation: 1718

How to get Auth::id() server-side on ajax post? It's returning null. Laravel 5.4

My user is authenticated.

To prove it:

axios.get('http://127.0.0.1:8000/api/user')
    .then(response => {
        console.log(response.data)
    })

...and the user info is logged to console as expected.

So experts, please tell me, how can I get Auth::id() on the server side on an ajax post??

Auth::id() returns null. It doesn't make sense that I would pass the user id with the data payload when the user is authenticated.

Upvotes: 1

Views: 598

Answers (1)

EddyTheDove
EddyTheDove

Reputation: 13259

Every route going through api, by default you need to do

$id = Auth::guard('api')->id; //OR 

$user = Auth::guard('api')->user();
if ( $user ) $id = $user->id;

You could do it in one line

$id = Auth::guard('api')->user()->id;

But if the user fails, you will receive Cannot get property id of null

Upvotes: 1

Related Questions