Search code examples
javascriptphplaravelcookieslaravel-5.5

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.


Solution

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