deo_gemini
deo_gemini

Reputation: 23

to check authenticated user and handle session time

I have this mechanism of checking the logged-in user role in a blade page so that I can give him/ her the selected pages but I find after a user has logged in and stayed idle for a long time and when he is back and wants to continue in the page he is getting an error

ErrorException Trying to get property 'id' of non-object (View: /var/www/html/poss_v1/resources/views/dashboard/student/index.blade.php)

and my code is here below

<?PHP
$user = Auth::user();  
$user_id = $user->id;    //----here is the problem it is missing the id when the session has ended--//
$role_user = App\Models\RoleUser::where('user_id', $user_id)->first();
$role_name = App\Models\Role::where('id', $role_user->role_id)->first();
$role = $role_name->name;
?>

Upvotes: 0

Views: 583

Answers (3)

Khayam Khan
Khayam Khan

Reputation: 1235

@php
    if(Auth::check()){
        $role_user_id = App\Models\RoleUser::where('user_id', auth()->id())->first()->role_id;
        $role = App\Models\Role::where('id', $role_user_id)->first()->name;
    }
@endphp

Upvotes: 1

Engr Talha
Engr Talha

Reputation: 404

In Laravel blade file you should check logged in user in this way.

@php
if(Auth::check()){
$user = Auth::user();  
$user_id = $user->id;
$role_user = App\Models\RoleUser::where('user_id', $user_id)->first();
$role_name = App\Models\Role::where('id', $role_user->role_id)->first();
$role = $role_name->name;
}
@endphp

Upvotes: 1

SillasSoares
SillasSoares

Reputation: 382

To increase the lifetime of your session, you may modify the env variable SESSION_LIFETIME to whatever minutes you wish.

And to make sure your user doesn't get this error, you may check if the session is still alive with Auth::check()

Upvotes: 0

Related Questions