1

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?

Maren Maren
  • 59
  • 1
  • 2
  • 8
  • 1
    Possible duplicate of [auth()->user() is null in Laravel 5.2](https://stackoverflow.com/questions/34504046/auth-user-is-null-in-laravel-5-2) – Loek May 30 '18 at 11:09

4 Answers4

3

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
Winner1
  • 1,261
  • 2
  • 12
  • 17
1

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.

Kul
  • 198
  • 1
  • 11
1

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
Sujan Gainju
  • 4,273
  • 2
  • 14
  • 34
0

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

Sumon Sarker
  • 129
  • 2
  • 10