Home > Net >  to check authenticated user and handle session time
to check authenticated user and handle session time

Time:11-09

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;
?>

CodePudding user response:

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()

CodePudding user response:

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
  • Related