Stem Florin
Stem Florin

Reputation: 872

Find out If user is loged in (Laravel) in frontend

so I come to you with a simple question: how is laravel session relay working.

My use Case: I have a laravel site cached with a varnish like so :

  1. every get request is made as the user is not logged in
  2. any user related info if loaded via ajax after the user loaded the page.

My problem is that I need to know in my front end if a user is logged in.

Things that I noticed:

  1. Laravel session is not accessible in js
  2. Laravel session is there even if the user is not logged in

I also tried to set my own cookie on login and unset it in on logout, but it my cookie is randomly diapering while the user is still logged in.

If someone has any idea on how to find out if my user is logged in from the standard cookies I would be so grateful.

Upvotes: 2

Views: 2045

Answers (3)

Fahad Khan
Fahad Khan

Reputation: 21

you can generate a token whenever a user is logged in and send it to the front-end and save it in the cookie. The cookie can have and the expiry time of say 5 hours. If during these 5 hours, user sends some requests, then the token is refreshed and 5 hour time starts again. In case, no request comes to the backend it means user is not active and you can log him out.

Upvotes: 0

Amol Rokade
Amol Rokade

Reputation: 152

You can use in JS var userCheck= " <?php echo Auth::check();?> "; , then check if userCheck is equal to one then user is logged In otherwise not.

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

Reputation: 163788

You can pass the data to JS like I'm showing in my repo. For example:

<input id="authenticated" type="hidden" value="{{ auth()->check() }}">

And then get the data which will be true or false:

let authenticated = $('#authenticated').val();

Alternatively, you could use an Ajax call and execute auth()->check() in a controller method.

Upvotes: 3

Related Questions