how to manage a special error with special message

2019-03-04 12:36发布

问题:

I'm using laravel 5.4. and I need handle some error. imagine user logged in and opened two windows (his profile). When user click on logout in a window, we have still logout button in another window, and by clicking on that, laravel will show csrf_token error page.

My logout in not ajax and its with submitting a form to /logout how can I handle this error with special message or redirect to home without error from logout controller? (not all of csrf_token errors, just from that controller).

logout form :

i will submit this form by clicking on logout button using jquery:

<form id="logout-form" action="/logout" method="POST" style="display: none;">
    <input type="hidden" name="_token" :value="token">
</form>

And the logout method in controller :

public function logout(Request $request)
{
    $this->guard()->logout();
    $request->session()->flush();
    $request->session()->regenerate();
    return redirect('/');
}

回答1:

in App\Exceptions\Handler.php Return the user to the form with a new valid CSRF token, so the page will refreshed and logout button will not exist.

public function render($request, Exception $exception)
{ 
   if($exception instanceof TokenMismatchException)
   { 
      return redirect()
               ->back()
               ->with('your msg');
   }
   return parent::render($request, $exception); 
}

this looking like, page was refreshed.

Don't Replace POST with Get. It will not Safe And Standard.



回答2:

One way is use GET for your logout. In fact use a simple <a href="/logout">logout</a> should be sufficient. So you change your route to use get and you can wave bye to the form.

Although, there might be different opinions about the METHOD to use but truthfully, this is sufficient.

Update

Isn't any way to manage errors just like what i said?

In my opinion, this is the best I would do for now. Otherwise to show special message when someone tries the logout route even though they are logged out, I will just do the following:

public function logout(Request $request)
{
    if (!auth()->check()) {
        return redirect('/')->with('login_error', 'You are already logged out please login again'); // message can be retrieved in session()
    }
    $this->guard()->logout();
    $request->session()->flush();
    $request->session()->regenerate();
    return redirect('/');
}

I will still not use post, since I am not creating any resource.

I hope this helps.