Deep Dive into Laravel Redirect Method

Deep Dive into Laravel Redirect Method

Laravel redirect is a global helper function of Laravel 6 frameword which can be used to redirect a user to different URL. Laravel provides us many useful helper functions, redirect() is one of them.

In this guide, I will walk you through the different usage of Laravel redirect function. We will look at how we can redirect a user to a page or action, with our without data attached to the response.

All responses in the Laravel framework are instances of the Illuminate\Http\RedirectResponse class which adds the proper headers needed for any redirection.

For the sake of this post, I will assume you are working in a Controller method, where you have performed the main actions. And now you want to redirect the user to somewhere in your application.

Laravel Redirect To URL

We will start by looking at the simplest usage of the redirect() method first. To redirect a user to the homepage of the website you can use the below method.

return redirect('');

Now if you pass anything within the redirect() method, that will be considered as a parameter. This will be added to the base URL of your application.

return redirect('welcome');

Above usage will redirect the user to the Base URL/welcome. Similarly, you can pass the more parameters using the forward slash.

return redirect('admin/dashboard');

Laravel Redirect Back

Apart from just using the redirect() method, there some other methods available which you can chain to the redirect method.

Consider you want to send the user back to the previous location after performing some data validation, you can chain the back() method.

return redirect()->back();

Extra Tip

You can also you the return back(); method if you are not willing to use the redirect() method. Because we are convering the redirect() method so I will focus on the main topic of this post.

Laravel Redirect To Route

Some developers prefer to use the named routes in their applications so their codebase stays consistent. Instead of using the URLs in the redirect method, you can also call the named routes just like we called the back() method after the redirect method.

Consider we want to send the user back to the list of our posts after storing a new post. We will use the named route to redirect our visitors.

return redirect()->route('posts.index');

The route() method also take the second parameter which is an array. In an array, you can specify the routes parameter.

Consider we have a route which loads the edit screen of a post.

Route::get('post/{id}', '[email protected]')-name('post.edit');

We can return to this route using the below code snippet.

return redirect()->route('post.edit', ['id' => $post->id]);

If you have only a single parameter you can also use it like below.

return redirect()->route('post.edit', $post->id);

Using the redirect to a named route is very useful if in future you want to change the structure of URLs, you don’t need to update the URLs as all the redirects will point to the given route name.

I mostly use the named routes for all Laravel redirects in my applications.

Redirect with Data

So far we have seen how we can redirect a user to URL, route or back to the previous location. You might have a scenario where you want to redirect user but also you want to send some addition data.

Laravel redirect method provides two chaning methods with() and withInput() which you can send the data with a redirection.

Firstly we will see how we can use the with() method. Have a look at the code example below.

return redirect()->back()->with('success', 'Post saved successfully.');

Above example will redirect the user back to the previous location and add a key success with value into the session flash data. You can retrieve the key success in the controller or blade view like below.

session('success');

What is Flash Data?

Laravel has concept of flash data which is available for only one request, after that it gets deleted from the session.

You can also chain multiple with() methods if you want to send some messages or data like below.

return redirect()->back()
->with('success', 'Post saved successfully.')
->with('post_id', $post->id);

Other neat solution will be to use an array to add all the information you want to send with the redirect, then pass that array to the with() method.

$response = [
    'success'   =>  'Post saved successfully.',
    'post_id'   =>  $post->id,
];
return redirect()->back()->with($response);

As you can see above code example looks more readable than the previous one.

Now if you are redirecting back after a form submission, use the withInput() method. This method doesn’t take any parameter and store the form values into the session.

Then in your blade view, you can use the old($key) method to grab the submitted value of a specific key.

Redirect to Controller Action

In Laravel, you can also redirect to the controller actions just like the Symfony Framework. Use the action() method to redirect to a controller action.

return redirect()->action('[email protected]);

If you want to pass a parameter to the controller’s action you can add that as a second parameter to the action() method like below.

return response()->action('[email protected]', ['id' => $post->id]);

In a real scenario, you might want to send the user to a controller action, but it’s recommended to use the routes for redirection.

Conclusion

That’s all from me know. Just like other awesome features offered by the Laravel, redirection made stupidly easy with the help of the redirect method. Always use the code standards and try to adopt the code style which other professional developers adopt in their applications. Learn more about the Laravel redirect method (if I have missed anything) on the Official Documentation on Laravel.

If you have any question about this post, please leave a comment in the comment box below.

Your little help will keep this site alive and help us to produce quality content for you.