Felix Eve
Felix Eve

Reputation: 3864

Laravel SPA get user on route that does not require auth middleware

In my controller's construct I specify the middleware:

public function __construct()
{
    $this->middleware('auth:api')
        ->except(['index', 'show']);
}

It's easy to get the user for any routes with the auth middleware by doing:

public function save(Request $request)
{
    $user = $request->user();
}

But I can't work out how to get the user for routes that allow anonymous users to access them and don't use the auth middleware:

public function show(Request $request) {
    // $request->user(); - this returns NULL

    // How can I get the user here?
}

When I use Chome's inspect network tab I can see this in my request header:

Authorization:Bearer kGncvh4IlotxIw2zY80GCnQPTMGyPZKGXntsHzsav2DPvffFfZZG60h74rsE

But what would I need to do to get the user object from this?

Upvotes: 0

Views: 485

Answers (1)

Felix Eve
Felix Eve

Reputation: 3864

I figured it out by reading this blog post.

The magic line of code is:

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

Upvotes: 3

Related Questions