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

claudiorigo's avatar

ErrorException, Attempt to read property "name" on null, {{ Auth::user()->name }}

The login works fine, this happens when I leave the computer alone for a few hours and when I return it throws an error message Auth::user()->name, in the dashboard this must be because the session expired, but the query is I can control this? something that sends the user back to login instead of sending this error.

0 likes
5 replies
vincent15000's avatar

When the session expires, the user is logged out.

Then when you refresh the page, the application attempts to show the current page and tries to get the name of the user, but there isn't any user logged in any more.

To avoid the error, you can for example :

  • protect the routes with the auth middleware

  • wrap the Auth::user()->name within @auth ... @endauth

1 like
Snapey's avatar

Sounds like you are not protecting dashboard access from guests

@vincent15000 has the right idea

1 like
claudiorigo's avatar

@Snapey I think it has to do with the time of the session that is in config/session.php but what I am looking for is to be able to capture this error and return it to login and not show me the web with the error. although if I do F5 to update the error disappears. then it could also be some cache.

danichurras's avatar

@claudiorigo do as @vincent15000 suggests and use a middleware. I would create a new middleware like this:

class RedirectIfSessionExpired
{
    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param Closure $next
     * @param string|null $guard
     * @return mixed
     */
    public function handle($request, Closure $next, $guard = null)
    {
        if (!Auth::guard($guard)->check()) {
            return redirect('/login')->with('your-session-error-key', "Time's up... Login again bruh");
        }

        return $next($request);
    }
}

and then assign it to your routes.

read https://laravel.com/docs/10.x/middleware#defining-middleware

Please or to participate in this conversation.