Home » Php » php – Laravel 4 – Redirect back to the same page where the request comes from

php – Laravel 4 – Redirect back to the same page where the request comes from

Posted by: admin April 23, 2020 Leave a comment

Questions:

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.

How to&Answers:

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');

Answer:

In Short: Yes

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.

Also….

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).

Just a snippet [untested]…

// [[... 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

Answer:

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.)