In this tutorial you will learn about the Laravel Redirections and its application with practical example.
What is Redirection?
Redirect responses are used to redirect the user from one URL to another URL. In Laravel, simplest way to return redirect response is to use global “redirect” helper method.
Redirecting To Named Routes
If you want to generate a RedirectResponse to a named route, it can be done using “route” method in following way –
Syntax:-
1 |
return redirect()->route('routeAlias',[params]); |
Example:-
1 |
return redirect()->route('dashboard'); |
If you are redirecting a route that expects parameter, we can pass them in second argument of the “route” method.
1 |
return redirect()->route('dashboard', ['role' => 'admin']); |
Redirecting To Controller Actions
If you want to return a redirect response to a controller action, it can be done using “action” method. Keep in mind to pass controller and action to it.
Syntax:-
1 |
return redirect()->action('ControllerName@actionName',[params]); |
Example:-
1 |
return redirect()->action('UserController@dashboard'); |
If you are redirecting a route that expects parameter, we can pass them in second argument of the “action” method.
1 |
return redirect()->action('UserController@dashboard', ['role' => 'admin']); |
Redirecting With Flashed Data
It is also possible in Laravel to pass flash session data while redirecting to a route, flash session data is availble upto only one redirect.
Example:-
1 |
return redirect('dashboard')->with('status', 'Profile updated!'); |