Laravel has a useful function redirect() to, well, redirect a user to a different page or action, with or without data. Let’s discuss those various options in one place – maybe you will find out something new for yourself.
Notice: if you use Laravel 4, note that those functions changed and were simplified in Laravel 5 – for example, instead of Redirect::to() in new version we use just redirect().
For all the examples I will use a case of a Controller method, where the main action has been done, and now at the end it’s time to redirect a user somewhere. So typically, the code snippets below represent the last row of Controller method.
Simple Redirect
This one is pretty straightforward – so if, for example, your website is www.website.com, it would redirect a user to the main URL + whatever you say in the parameter:
return redirect('homepage');
Redirects to http://www.website.com/homepage
return redirect('auth/login');
Redirects to www.website.com/auth/login
return redirect('');
Redirects to the main page – www.website.com
Chaining Methods and Redirecting Back
If you just want to redirect a user back to the previous page (the most common example – is to redirect back to the form page after data validation failed), you can use this:
return redirect()->back();
As you see in this example, you can add more methods to redirect() – even more than one, we’ll see that in the next example.
Go to QuickAdminPanel.com
Redirect with Data
There are two methods which allow to send some data with the redirect. Firstly, you can just use with():
return redirect()->back()->with('error', 'Something went wrong.');
This code will add an item to the Session Flash Data, with key “error” and value “Something went wrong” – and then you can use that in the result Controller or View as session(‘error’).
Laravel has a concept of Session Flash data for only one request – after the next is loaded, that Session element/value is deleted, and can’t be retrieved again. This is exactly what is happening in with() method – its purpose is to add an error message or some input data only for that particular redirect and only for one page. It does the same thing as a function Session::flash(‘error’, ‘Something went wrong.’).
You can also put several with() methods, one after another – it will save both entries into the Session:
return redirect()->back()->with('error', 'Something went wrong.')->with('order_value', $value);
But a more convenient way of doing that is to use arrays:
$parameters = ['error' => 'Something went wrong.', 'order_value' => $value]; return redirect()->back()->with($parameters);
If you’re redirecting back to the form, a really useful method is withInput():
return redirect()->back()->withInput();
This method has no parameters and what it does is saves the old form values into Session. Then in the form you can use function old($key) to retrieve those values for every field – that would be a separate topic about the Forms.
Redirect to a Route
If in your routes.php file you have a route with a name, you can redirect a user to this particular route, whatever its URL is:
app/Http/routes.php:
get('books', ['as' => 'books_list', 'uses' => 'BooksController@index']);
app/Http/Controllers/SomeController.php
return redirect()->route('books');
This is really useful if in the future you want to change the URL structure – all you would need to change is routes.php (for example, get(‘books’, … to get(‘books_list’, …), and all the redirects would refer to that route and therefore would change automatically.
And you can also use parameters for the routes, if you have any:
app/Http/routes.php:
get('book/{id}', ['as' => 'book_view', 'uses' => 'BooksController@show']);
app/Http/Controllers/SomeController.php
return redirect()->route('book_view', 1);
In case of more parameters – you can use an array:
app/Http/routes.php:
get('book/{category}/{id}', ['as' => 'book_view', 'uses' => 'BooksController@show']);
app/Http/Controllers/SomeController.php
return redirect()->route('book_view', [513, 1]);
Or you can specify names of the parameters:
return redirect()->route('book_view', ['category'=>513, 'id'=>1]);
Redirect to a Controller Action
The last piece of the puzzle is that you can redirect to a specific Method of a specific Controller, no matter what its Route or URL is – use method action():
return redirect()->action('App\Http\Controllers\BooksController@index');
Note that if you worked with Laravel 4 previously, that in Laravel 5 you have to specify the whole path to the folder like that. Not very convenient, and in general I haven’t seen much redirecting to specific actions in production code, the best and perhaps the most flexible way is to do it to named routes.
Like in routes, you can redirect to the action with parameters – identical to the redirecting to routes with parameters, just put in the value or array of values as a second parameter of action() method:
return redirect()->action('App\Http\Controllers\BooksController@show', [1]);
So, that’s pretty much all the options of Laravel for redirecting the user to any page you want with any parameters you want. The most important trick here is not to redirect to the same page/action and not to cause eternal loop 🙂
return back(); works like return redirect()->back();
pretty much all the options of Laravel for redirecting the user to any page you want
Thank you. It helped me much
Well written, incredibly helpful. Thank you!
This information is very helpful for me, thanks
So “`redirect()->to(”)->with(‘message’, ‘Hello’)“` will not worlk?
Didn’t test it, but should work. Don’t see any reason why it shouldn’t.
Hi I did not test it yet, but I think reson is in web middleware. Like in this answer http://stackoverflow.com/questions/34562501/laravel-5-redirect-with-message?noredirect=1#comment56868726_34562501
How to force to redirect instantly (return redirect(“login”)) if you are in sub class or in parent class? In 4.2 ti works but in 5.2 it does not .
I am using 5.2 and I can’t make that my form get the information with old and repopulates it.
I am using > Laravel 5.1 and
Working in the back area. Have a session created in Method A, now I want to access in the B method on the Session. after the redirect the values are lost?
Can someone help me please. Maybe it has to do with it I’m in the back area. The rights are set correctly.
How do you return back to an index part of a single page setup? ie #register or #login?
just use
return Redirect::to(URL::previous() . “#login”);
return Redirect::to(URL::previous() . “#register”);
And remember to import it at the top:
use Illuminate\Support\Facades\Redirect;
use Illuminate\Support\Facades\URL;
Careful! The Laravel redirect() and Redirect::to() both do a 302 “temporary” redirect. That tells the web browser to go to the other page. But if the page on your site permanently moved, you need to do a “301” redirect to tell Google and other search engines that the new page is the correct one. For that you have to pass “301” as the second paramenter, such as redirect(‘auth/login’, 301).
Great one David,
What if I redirects with this function?
return redirect()->secure($request->getRequestUri());
Where should I place the 301 part?
You can do this:
return redirect()->secure($request->getRequestUri(), 301);
how to redirect user to an url by user click, for example i send an email with url that redirect to my website, but to access that pages user must login first, my question is how to pass that clicked url to the controller so that i can then use that to redirect the users after successfully logged in?
thank you so much for any answer. really appreciate it.
“return redirect()->back()->withInput();” made my day
thanks a lot
I am not able to access laravel redirect with parameters.
I am using
return redirect(‘/myroute’)->with(‘var’, $var_value);
how to access var in myroute?
public function update(Request $request,note $note,card $card)
{
# code…
$note->update($request->all());
return redirect(‘cards/’);
}
I have such code and on completion, i want to redirect to cards/card, where card is id of particular card
Hi!! Thanks a lot. You make my day.
return back()->withInput();
works if in the form the old key is used, like:
I repeat… thanks a lot
this one helped me..
return redirect()->back();
thank you.
Hey
Can you please clear my doubt
I m using ajax in which i m call a controller method
in that method i m calling another method (payment gateway method for paypal)
in the gateway method my redirection code is there
its not working
i hope you get my ans
if yes then please clarify how can i use that redirection method
After data has been passed to a controller with redirect()->action() how does the controller access the data?
Lovely. I want to redirect to the same tab after form submission;
In Controller:
return redirect(‘/profile/edit/profile#tab_1_2’)->with(‘message’,’Education Record Updated’);
JQuery:
$(document).ready(function () {
if (window.location.hash == ‘#tab_1_2’) {
$(‘li.tab_1_1’).removeClass(‘active’);//remove active class
$(‘div#tab_1_1’).removeClass(‘active’);
$(‘li.tab_1_2’).addClass(‘active’);
$(‘div#tab_1_2’).addClass(‘in active’);
}
});
It reloads the first tab_1_1 before loading the second tab_1_2.
How do I make it reload to the second tab directly?
None of them worked for me. I created a page that is the action of a form and put logic for inserting post variables to the db and a redirect. Thats all. the page doesnt have css and is just meant to redirect to another
a displaying page after inserting data in db. return redirect(‘blabla’); Redirect::to(‘blabla’); return Redirect::to(‘blabla’);and return redirect()->route(‘blabla’); dont work for me. boo hoo. I even have a headache now from trying with no solution. some of the other things I had tried I have even forgotten. Anyone with a one time working result debug free.