Last updated on August 2, 2023
In programming, we redirect class to class and also method to method based on data or conditions. Laravel 9 and previous versions have functions that help to redirect one place to another.
Sometimes we redirect one place to another in both small and large-scale applications based on conditions. In this article, we will be covering situations where redirects are needed.
In the Laravel framework, redirecting one URL to another is very easy. It has a globally accessible redirect() method that takes a URL or slug to redirect. To redirect to the home page of the application just pass the forward slash as the first argument.
return redirect(‘/’);
This method redirects to any URL of the application. Let’s suppose we redirect to the contact page
return redirect(‘/contact-us’);
The above script redirects to the contact us page. We can also send data to the page, following is an example.
return redirect(‘/contact-us’, [‘id’ => 10]);
In Laravel, we create routes for every form to post data and after posting data we show a success message to the user or redirect further to the thank you page. But in some cases, we redirect back users to the previous form, for example, if incoming data has an error or incomplete information. To inform the user we show a message that explains the reason why the system couldn’t proceed and send it back to the previous form.
Let’s suppose we have a form that stores email addresses for free movie tickets.
<form action="{{ route('formPost') }}" method="post">
@csrf
<input type="email" name="email_address" />
<input type="submit" />
</form>
When a user post this email address form, Laravel sends a request to the formPost
route that is bound to the store method from UserController
. In the store method, we redirect back to the email address form with an error message through redirect(), back(), and with() method. These methods are chained together.
public function store()
{
return redirect()->back()->with([
'free_ticket_message' => 'We have distributed all free tickets, please try next time.'
]);
}
Then in the blade file following script checks if there is a message for free tickets in the session.
@if (\Session::has('free_ticket_message'))
{!! \Session::get('free_ticket_message') !!}
@endif
Above if-statement checks message in the session and shows it in the HTML element.
Laravel’s built-in route()
function redirects to the provided route. It takes the route name in the first argument and also it has a second optional parameter that accepts data in array format. Data can be passed as a second argument in the route()
method.
Let’s understand with an example, suppose a web application provides keyword research service and it has a subscription module that restricts non-subscribe users to use the application. Every time, when a user searches for a keyword, the application checks the user’s subscription status. If the system finds the subscription status false it redirects the user to the subscription route where the user subscribes to the service.
if($subscriptionStatus === false){
return redirect()->route('buySubscription');
}
Further, if any data needs to be sent along with the route, pass it as a second argument. For example, if a website has a $5 discount offer for users who didn’t purchase a subscription yet then an array with the discounted amount and key can be sent along with the route. Below is an example.
$discount = 5;
if($subscriptionStatus === false){
return redirect()->route('buySubscription', [‘discount’ => $discount]);
}
Redirect with a Success Message
In case if you want to redirect to the route with message then you can use the “with” method to attach a success message.
return redirect()->route('route.name')->with('success', 'Your success message here!');
Redirect with an Error Message
Similarly, you can attach error message through “with” method.
return redirect()->route('route.name')->with('error', 'Your error message.');
Laravel allows us to redirect to any controller’s method in the application. For that, it provides an action() method that chains with the redirect()
method.
This can be used in different flows, let’s discuss a situation where this kind of redirect can be helpful. Suppose a Laravel application monitors activity continuously and redirects to the logout method if the user does not use it for a few minutes.
return redirect()->action([HomeController::class, 'index']);
You can use the redirect() method to redirect user in the Laravel framework that accepts URL and slug. Also, you can attach data in array format. There are a few methods such as back(), and with() that help in sending data to redirect URL, redirecting to previous URL, etc. These methods can be chained with the redirect() method.