Laravel Redirection

Redirection means to send from one location to another one. Laravel provides ‘Redirect’ Facade and ‘redirect()’ to redirect the user.

I am using Laravel 5.4 here. You can redirect user with following different methods:

  • redirect()->to(‘URL’);
  • redirect()->route(‘route_name’);
  • redirect()->back();
  • redirect()->action(‘action’);
  • redirect()->intended(‘URL’)

Let’s see practical examples here:

redirect()->to() is used to redirect on specific URL. In this case, suppose I want to redirect the user to post page then I can use something like this:

You can notice with(). The with() method that method will help you to send variables or parameters to the URL. Remeber that You can write the same syntax with Redirect facade also like this:

To redirection on a route, you can use Redirect::route(). For example:

Redirect::back is used to redirect to back URL mean URL from where your user request was fire.

Redirect::action will execute specific action or method of the controller. For example

in this case, you will note that index method will execute.

Rediect::intended will use when redirect is not defined. very prectile use of this is when user current login session is expired. Here is the good example for some of this methods:

Now I am going to create new Controller called TestController

When you playing around form and user input wrong data then you can check validations and redirect back to the last URL. Something like this:

To redirect on other domain you can use Redirect::away()

Simple example but I think it’s good to explain the purpose. for more about redirections, you can check here.

Leave a Reply

Your email address will not be published. Required fields are marked *