Laravel Named Routes

Named Routes

Named routes allow the suitable generation of URLs or redirects to specific routes.
We specify a name for a route by changing the name method onto the route definition:

Syntax:

 Route::get(‘user/profile’, function ()
 { 
 // 
 }) -> name(‘profile’); 

We also specify a route names for controller actions:

Syntax:

Route::get(‘user/profile’, ‘UserProfileController@show’) -> name(‘profile’);

Generating URLs to Named Routes

Once we have assigned a name to the given route, we use the route’s name when generating URLs or redirects via the global route function:

Syntax:

//Generating URLs
$url = route(‘profile’);
//Generating Redirect
return redirect() -> route(‘profile’); 

 If the named route defines parameters, we pass the parameters as the second argument to the route function.

E.g.:

Route::get('admin/posts/example', array('as' => 'admin.home' ,function() {
$url = route('admin.home');
return "The url is " . $url;
}));

Output:

Generating URLs to Named Routes

We can easily check our generated URL with the help of php artisan route:list command:

named routes

The given parameters will automatically be added into the URL in their appropriate positions:

Syntax:

Route::get(‘user/{id}/profile’, function($id)
{
//
}) -> name(‘profile’); 
$url = route(‘profile’, [‘id’ => 1]); 

Inspecting the Current Route:

If we would like to determine whether the current request was routed to a given named route, we use the named method on a route instance.

We check the current route name from a route middleware:

Syntax:

public function handle($request, Closure $next)
{ 
If($request->route()->named(‘profile’))
{ 
// 
return $next($request); 
}