LakiGeri
LakiGeri

Reputation: 2105

Laravel javascript logout

What is the best practice, if something wrong happens, in a client-side (of a laravel 5.4 project) in a JavaScript code, for example the code is not able to find the important cookies?

So how can I make a code what is automatically log-out the user (with an error message) if some error occours? Is there any simple library or method, what should I use in this case?

Thanks for the answers and suggestions in advance!

Upvotes: 1

Views: 2674

Answers (2)

QuickPrototype
QuickPrototype

Reputation: 883

The logout button masks the Javascript post that is used to trigger this action. You can simply use the same call on any page that has the logout button already created: i.e.

document.getElementById('logout-form').submit();

Upvotes: 2

Sandeesh
Sandeesh

Reputation: 11936

This is the default logout route in Laravel.

$this->post('logout', 'Auth\LoginController@logout')->name('logout');

Which looks like this

public function logout(Request $request)
{
    $this->guard()->logout();

    $request->session()->flush();

    $request->session()->regenerate();

    return redirect('/');
}

So if you would like to logout the user from JavaScript, then just send a post request to the logout route. This should logout and redirect them. But in case you want to gracefully logout and show error messages, you need to create a new logout method and have it send a json response instead of redirecting. Then call the newly created route and log the user out and throw the received message.

Upvotes: 2

Related Questions