Laravel - Redirects

A named route is used to give a specific name to a route. The name can be assigned using the "as" array key .
Route::get('user/profile', ['as' => 'profile', function () { // }]);
Note. Here we have specified the profile name for the route user/profile .
Redirecting to named routes
example
Take a look at the following example to understand more about redirecting to named routes.
Step 1 - Create a view named test.php and save it to
resources/views/ test.php
<html> <body> <h1> Example of Redirecting to Named Routes </h1> </body> </html>
Step 2 − In the route.php file, we have configured the route for the test.php file . We have renamed it Testing . We also set up another route redirect that will redirect the request to test the named route.
app/http/routes.php
Route::get('/test', ['as'=>'testing',function() { returnview('test2'); }]); Route::get('redirect',function() { return redirect()->route('testing'); });
Step 3 − Visit the following URL to check the named route example.
http://localhost:8000/redirect
Step 4 − After executing the above URL, you will be redirected to http://localhost:8000/test as we are redirecting to named test route .
Step 5. After successfully executing the URL, you will get the following output:
Redirecting to controller actions
Not only a named route, but we can also redirect to controller actions. We just need to pass the controller and action name to the action method as shown in the following example. If you want to pass a parameter, you can pass it as the second argument to the action method.
return redirect()->action('NameOfController@methodName',[parameters]);
example
Step 1 − Run the following command to create a controller named RedirectController .
php artisan make:controller RedirectController --plain
Step 2 − Upon successful execution, you will get the following output −
Step 3 - Copy the following code to a file
app/Http/Controllers/RedirectController.php .
app/Http/Controllers/RedirectController.php
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\Http\Requests; use App\Http\Controllers\Controller; class RedirectController extends Controller { public function index() { echo "Redirecting to controller's action.";
} }
Step 4 - Add the following lines to app/Http/rout.php .
app/http/routes.php
Route::get('rr','RedirectController@index'); Route::get('/redirectcontroller',function() { return redirect()->action('RedirectController@index'); });
Step 5 − Visit the following URL to test the example.
http://localhost:8000/redirectcontroller
Step 6 − The output will look as shown in the following image.