简体   繁体   中英

laravel 8 how to get user id using bearer token

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 ??

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;
}

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();
}

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

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

or

$request->user()->id

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM