baguus
272
0
Laravel

Call to a member function authorizeRoles() on null after session timeout

Posted 1 year ago by baguus

Hi guys I have a problem on how to catch a session timeout.

I have a function in my User model:

public function authorizeRoles($roles)
    {
        if ($this->hasAnyRole($roles)) {
            return true;
        }
        abort(401, 'This action is unauthorized.');
    }

In controller function

public function someFunction(Request $request) {
        $request->user()->authorizeRoles(['some_user_role']);
}

in Handler.php

public function render($request, Exception $exception)
    {

        if ($exception instanceof NotFoundHttpException) {
            return response()->view('error/404', [], 404);
        }

    /*    if ($exception->getStatusCode() == 401) {
            return response()->view('error/401', [], 401);
        }  gives white screen if session expired */
        return parent::render($request, $exception);
    }

When the session expires I get a

FatalThrowableError Call to a member function authorizeRoles() on null

here

$request->user()->authorizeRoles(['some_user_role']);

I guess the object doesn't exist anymore? How can I catch session timeout correctly. I would like to redirect to login or show a session expired page.

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.