Understanding Laravel Redirect method with Example

0
602
laravel redirect

Laravel redirect function is a global helper function that comes in handy in many cases during programming. There are various types of redirect in Laravel. In this article, we will deep dive into each type in detail.

1Redirect to URL

This is the simplest and most straightforward redirect usage in Laravel. We can simply give the URL where we want to redirect. This will redirect to any URL given as a parameter inside the redirect function. A well-explained example is given below.

//redirect to URL

return redirect('');

This will simply redirect to the homepage. It’s redirect output will be http://www.website.com/

//redirect to URL

return redirect('login');

This will redirect to the login page. Its redirect URL will be http://website.com/login

2Redirect Back

Laravel redirect helper function has a back() chain method. As the name suggests, it is used to redirect to the previous page. It comes in handy in multiple situations such as validation and operations. The below example will redirect back to the previous page.

//Redirect Back

return redirect()->back()

We can also redirect back with inputs as in the below example.

//Redirect back with inputs

return redirect()->back()->withInput($request);

In addition, we can also redirect back with a message as in the below example.

//Redirect back with message

return redirect()->with('success', 'Article successfully created.');
OR
return redirect()->withSuccess('Article successfully created.');

3Redirect to Route

In the first example, we redirected to the unnamed route URL. But, we can also redirect to the named route. This is a more common practice as we can use a named route without any changes even if there are changes in the URL.

// Redirect to route

return redirect()->route('article');

We can also pass parameters when redirecting using a named route.

// Redirect to route with parameter

return redirect()->route('article', $id); //single parameter

return redirect()->route('article', [1,2,3,4]); //multiple parameter

4Redirect to Controller Action

We can also redirect to a controller action. For this, we simply need to give a controller and action name. Using this redirect method, it doesn’t care what its URL is.

//Redirect to controller action

return redirect()->action('ArticleController@index');

In addition to this, we can also pass parameters to the action using the following method.

//Redirect to controller with parameter

return redirect()->action('ArticleController@index', [1,2,3,4]);

That is all about redirects in Laravel. Different programmers use redirects differently. So, what is your most used redirect method? Don’t forget to comment below. 🙂

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.