K Arun Singh
K Arun Singh

Reputation: 810

Laravel - Unable to access Sessions in render function of Exception Handler.php file

Say for 404 Exception handling I'm trying to display a 404 page separately for admin and front pages based upon the user session, following is my render function of Handler.php file

public function render($request, Exception $e)
{
    echo Session::has('user.id');
    ...
    ...
}

But Session::has('user.id') always returning null value and I'm unable to decide if the user is actually logged-in.

In one of my old Laravel projects I have used the same logic and is successfully working, current project Laravel version is 5.2.45

Thank you for your help.

Upvotes: 2

Views: 827

Answers (2)

Leon Vismer
Leon Vismer

Reputation: 5105

The problem you will have is at the point of a 404 error the StartSession middleware would not have run yet, so technically at the point the Exception is thrown the user information is not available yet.

One solution is perhaps to check specifically for endpoints like something containing an admin keyword /admin/doesnotexist, however is it limited as if your try just /testing the intention is not clear, is the users requesting a frontend or backend resource?

An alternative is something like:

public function render($request, Exception $exception)
{
    if ($exception instanceof NotFoundHttpException) {
        return redirect('/displaynotfound');
    }
    return parent::render($request, $exception);
}

Route::get('/displaynotfound', function() {
    // Do what you need todo, as you will have access to
    // to the user.
    dd(auth()->user());
});

Upvotes: 0

stefanzweifel
stefanzweifel

Reputation: 1454

I would recommend using the auth()-helper or Auth-Facade to retrieve information about the current logged in user and check if the user is logged in.

User ID

auth()->id();
Auth::id();

Check if user is logged in

auth()->check();
Auth::check();

https://laravel.com/docs/5.5/authentication#retrieving-the-authenticated-user

Upvotes: 0

Related Questions