Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

JoelPiccoli's avatar

Using the bearer token outside of a guarded route [SOLVED]

Hello guys! I'm facing an issue with one of my applications where I have a route that myght not be authenticable in some cases, and in this cases I need to pass my Authorization header as null to indicate that no user is related to that request. But in the other cases, I will pass the Authorization header as such and them get the related user that is atached to that request.

How can I do that? Becouse even when I pass the Authorization bearer token the auth()->user() still null...

0 likes
1 reply
JoelPiccoli's avatar
JoelPiccoli
OP
Best Answer
Level 2

Well, I don't if it is the best solution for this problem, but I created a middleware to fetch the user if any token if provided in the request headers. Solved the problem for me. ;) If any one have a better solution, please, be free to recomend it...

<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;

class FetchUserByBearerToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $bearerToken = $request->bearerToken();

        if ($bearerToken) {
            $user = User::firstWhere('api_token', '=', $bearerToken);
            \Auth::login($user);
        }

        return $next($request);
    }
}

Please or to participate in this conversation.