Home > Software design >  laravel 8 how to get user id using bearer token
laravel 8 how to get user id using bearer token

Time:10-30

I am working with laravel 8 and I need to access one of the API routes whether using a token or without a token for example I have a post page and if user is logged in I want to check if he like the post or not but if he is not logged in I just display the post.

I write the following code but I am getting an error 500

$bearer=$request->header('Authorization');
if(isset($bearer)){
            
            $fav=UserFav::where('user_id',request()->user()->id)->where('project_id',$id)->get();
            if(!$fav->isEmpty())
            $is_fav=true;
        }

the error message is

Attempt to read property id on null

I understand the message it says the request()->user() is returning null and that's because the route is not in sanctum middleware

but the problem if I put the route to sanctum middleware I will not be able to access it as guest so how I can get the user id or user according to bearer token sent in header ??

CodePudding user response:

Try this

if(!empty(request()->user())){ // Define user logged in
  $fav=UserFav::where('user_id',request()->user()->id)->where('project_id',$id)->get();
} else {
  $fav=UserFav::->where('project_id',$id)->get();
}

if(!$fav->isEmpty()) {
  $is_fav=true;
}

CodePudding user response:

Auth::check will give you if the user is authenticated, even if you're using brearer token

use Illuminate\Support\Facades\Auth;

$is_fav = false;
if(Auth::check()) {
    $is_fav = UserFav::where('user_id',Auth::user()->id)
                 ->where('project_id',$id) 
                 ->exists();
}

CodePudding user response:

I'm using passport instead of sanctum, and the way I do is

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

or

$request->user()->id
  • Related