Maren Maren
Maren Maren

Reputation: 69

Current user's ID in Laravel API

I have controller method store and defined api route for that method. When I try to store informations from $request everything is ok but current user ID. Auth::user() return null. How to grab that id?

Upvotes: 1

Views: 11816

Answers (4)

Sumon Sarker
Sumon Sarker

Reputation: 129

Laravel by default provide current user using laravel helper or laravel static method. Examle : default=>

 \Auth::user();

If you used any guard for this then just used

 \Auth::guard('guard_name')->user();

If you used api then you can get current user by

auth('api')->user() //it's a laravel helper

This one for api route above two for web route

Upvotes: 0

Winner1
Winner1

Reputation: 1526

According to @Rahul Reghunath answer in How to get current user in Laravel API using Passport?

you can try using this method to access user id in api middleware:

auth('api')->user();

an example:

Route::get("me",function (){
    $userInfo=auth('api')->user();
    if ($userInfo!==null)
    {
        return "User is logged in. id:".$userInfo->id;
    }else{
        return "User is not logged in.";
    }
});

for me it has shown the id when it authenticated with a bearer token:

User is logged in. id:6

Upvotes: 3

Sujan Gainju
Sujan Gainju

Reputation: 4769

If you are trying that from custom made auth ( not default auth provided by laravel ), then all your auth required routes should be using web middleware.

Route::group(['middleware' => 'web'], function () {
    // your routes
});

Then you can get the Active user id using either

Auth::user()->id

or

auth()->user()->id

Upvotes: 1

Kul
Kul

Reputation: 210

First, you need to make sure that "api user" is logged in to get ID. You can use auth()->user()->id or Auth::user()->id to get current user id.

Upvotes: 1

Related Questions