Skip to content
Advertisement

Laravel 5 withError() vs withErrors()

I could be doing something very stupid. Accidentally produced a piece of code which I cannot seem to figure out how it works.

I am trying to customize unauthenticated user redirection to login page. So when user tries to access a page that is protected, laravel redirects the user to the login page. I am trying to show a Javascript toastr message in such cases.

What i did was customize the unauthenticated method in AppExceptionsHandler.php class as follows:

protected function unauthenticated($request, AuthenticationException $exception)
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }
    //dd($request);
    return redirect()->guest('login')->withError('You are not logged in or Your session has expired');
}

Note that i missed the s in the withError function. In my blade file i am showing the toastr notification as follows:

<script>
 @if(Session::has('error'))

       toastr.error("{{Session::get('error')}}");
 @endif
 </script>

So whenever a user is being redirected to the login page because he is not logged in yet, a Java Script toastr message is shown. However, i cannot figure out how the Session('error') value is being populated by the withError function. I could only find that Laravel has withErrors function, not withError.

Tried to troubleshoot for last couple hours without luck. Seeking some guidance here. Thanks. Btw, i am very new to Laravel.

Advertisement

Answer

It’s a “magic” method, in that any call to a method with a prefix of with will be added to the session as flash data. So withError() will add flash data under the key error; withErrors() will add flash data under the key errors; withSuccess() will add flash data under the key of success; and so on.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement