Čamo
Čamo

Reputation: 4163

Laravel 5 redirect with message

Can someone explain why the code below does not work when it redirects to another page?

return redirect()->route('homepage')->with('message', 'I am so frustrated.');

The redirect works as expected, but the message does not appear.

The view looks like:

@if ( session()->has('message') )
    <div class="alert alert-success alert-dismissable">{{ session()->get('message') }}</div>
@endif

When I change it to:

return redirect()->route('contact')->with('message', 'I am so frustrated.');

, which is the same as redirect()->back(), everything works fine and the message is displayed. What is the difference between redirect back() and to() another view?

Upvotes: 5

Views: 20470

Answers (2)

user6221709
user6221709

Reputation:

I am currently on Laravel 5.7 HTTP Redirects and this code worked for me in the Controller:

public function register(Request $request)
{
    $this->validator($request->all())->validate();
    event(new Registered($user = $this->create($request->all())));

    return $this->registered($request, $user) ?: 
    redirect($this->redirectPath())->with('success', 
    'An activation link was send to your email address.');
}

And in the View (etc.blade.php) i do:

@if(session('success'))
     <span class="alert alert-success" role="alert">
         <strong>{{ session('success') }}</strong>
     </span>
@endif

Upvotes: 1

patricus
patricus

Reputation: 62228

If you're on Laravel 5.2, make sure all the routes you're using that access session data are contained in the web middleware group.

If your contact route is inside the web middleware group, but your homepage route is not, that would explain your issue.

Upvotes: 6

Related Questions