Search code examples
laravelauthenticationroutesmiddlewareerror-messaging

How can I use auth middleware's redirectTo method with url parameter and error message?


All I want to do is use a URL with a language parameter that results in the error message which I want to show the user. If I execute the commented code, I get the error;

Header may not contain more than a single header, new line detected.

On the other hand, if I execute my code that is not included in the comment, I get an error;

Call to a member function with () on string.

I know the reasons for the mistakes. However, I am looking for a solution to achieve my goal.

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            // return \Redirect::route('login', app()->getLocale())->with('error', 'Error message');
            return route('login', ['locale' => app()->getLocale()])->with('error', 'Error message');
        }
    }
}

Solution

  • You can not call with() on the route() method, because the route() method only returns a string and is not in charge of a redirect.

    If you would need to show an error message to the user after the redirectTo() method has been called, i think you can rather just keep the error message in Laravel Session

    https://laravel.com/docs/8.x/session#interacting-with-the-session

    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
    
            // This next line keeps the error message in session for you to use on your redirect and then deletes it from session immediately after it has been used
            $request->session()->flash('error', 'Error message!');
    
            return route('login', ['locale' => app()->getLocale()]);
        }
    }
    

    You can now view the error message as you would normally:

    In your controller:

    $request->session()->get('error');
    

    OR from your view:

    {{ Session::get('error) }}