Reputation: 4175
In Laravel 4, I want to redirect the user back to the page from where the request came. For example, a user tries to update his profile so edits the profile and hits SAVE. In controller I do the update and normally I would do Redirect::to('profile')->with('message','Profile saved!')
. But what I want is to simply redirect it back with message. May be something like Redirect::back()->with('message','Operation Successful !')
if this is available. I want it as it is more generic and I can use it anywhere.
Upvotes: 43
Views: 101669
Reputation: 304
return redirect()->back()->withMessage('Profile saved!');
Or,
return back()->withMessage('Profile saved!');
or
return Redirect::back()->withMessage('Profile saved!');
Upvotes: 3
Reputation: 451
You should consider not to use Redirect::back()
. Yes, it's tempting and seems to be exactly what you need. But:
The back()
method uses the "referer" attribute of the request header. So the user agent, usually a browser, tells the server (and Laravel) the URL he comes from. (as Wikipedia says: referer is a misspelling of referrer) But not every user agent / browser will provide this information! I use Opera and I do not allow it to transmit the referer in generally! So back()
won't work for me. (Yes, I can allow this for a site but I'm way to lazy. And sorry, I don't trust your site.)
Upvotes: 6
Reputation: 4791
You can certainly use
Redirect::back()->withMessage('Profile saved!')
in place of
Redirect::to('profile')->withMessage('Profile saved!')
*nifty feature in Laravel that it parses your camelCase on the ->with('name', 'value')
so that ->withName('value')
works just the same.
I'm assuming your form is bound to the model such as Form::model($user, [...]
to pre-fill form fields, but if not you may want to re-flash the input on the Redirect (or if your validation failed and you want to user to be able to correct the invalid info).
// [[... validation and other magic here]]
if ($validator->fails()) {
return Redirect::back()
->withMessage($message_fail)
->withErrors($validator)
->withInput();
}
return Redirect::back()
->withMessage($message_success)
Hope that helps!
Twitter: @ErikOnTheWeb
Upvotes: 21
Reputation: 87719
Yes this is available:
return Redirect::back()->with('message','Operation Successful !');
But since this is a redirected request, you have to access the message by using:
echo Session::get('message');
Upvotes: 93