What are redirect routes? They are routes
or URI that take an end-user to a page or resource different from the requested one. This can happen when a user has been authenticated and is taken to their dashboard, or when an end-user tries to access a page where they have no permission. Several reasons can call a redirect route in an application.
In Laravel, redirect responses are instances of the Illuminate\Http\RedirectResponse
class.
The simplest method to generate a RedirectResponse
is to use the global redirect()
helper. Do not forget to import the instance of the class.
A redirect response can be initiated from a route
or a Controller
, the simplest way of instantiating it from the route.
Route::get('/login', function () {
return redirect('/home/dashboard');
});
From the above code block, we notice that the user tried the uri
login and was redirected to the /home/dashboard
uri
.
As stated above, one of the reasons for a redirect can be to send the user back
to the login page if their entry fails authentication. This can be done using the global back
helper function. Ensure that the route calling the back function uses the web middleware group or has all of the session middleware applied.
Route::post('/user/dashboard', function () {
//validate request
return back();
});
Normally, from the Controller
, we would like to return a view
where the data can be displayed.
return view('home.dashboard');
However, when it comes to redirecting the user to another route
, we use:
return redirect()->route('home');
This would take the request to a home
uri
, not the view
where the application would further process it. Always make sure to call the Illuminate\Http\RedirectResponse
class to avoid throwing errors.
This was just a touch-up on the basics of redirect routes as they are more advanced.
Redirect routes basically take a user a uri
other than the one they requested.