What Is Named Routes In Laravel Framework With Example

admin_img Posted By Bajarangi soft , Posted On 17-09-2020

Named routes is an important feature in the Laravel framework.Named routes allow the convenient generation of URLs or redirects for specific routes.it means naming route will give nickname for the route.

What Is Named Routes In Laravel Framework With Example

Named routes allow a convenient way of creating routes. The chaining of routes can be specified using name method onto the route definition.
The following code shows an example for creating named routes with controller 

Route::get('employee/details', function () {
    return '<h1>Am Employee No 1</h1>';
})->name('details');
 

We can also specify the named routes for controller actions:

Route::get('employee/details', 'employeecontroller@showdetails') -> name('employee_details');


Generating URLs to named routes
 

Once you assigned a named route to a given route, then you can use the name of the route while generating URLs or redirecting through a global route function.

//Generating URLs 

$url= route('employee_details');

//Generating Redirects... 

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


Suppose we have many parameters in the URL; in this case we can provide the short name to the URL. We use an array which wraps everything, and it appears as a second parameter in a get() function. Let's understand through an example.

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


If the named route defines parameters, you may pass the parameters as the second argument to the route function. The given parameters will automatically be inserted into the URL in their correct positions:

Route::get('employee/{id}/details', function ($id) {
        //
})->name('details');

$url = route('details', ['id' => 1]);



If you pass additional parameters in the array, those key / value pairs will automatically be added to the generated URL's query string:
 

Route::get('employee/{id}/details', function ($id) {
        //
})->name('details');
$url = route('profile', ['id' => 1, 'photos' => 'yes']);


Inspecting The Current Route

If you would like to determine if the current request was routed to a given named route, you may use the named method on a Route instance. For example, you may check the current route name from a route middleware:
 

public function handle($request, Closure $next)
{
        if ($request->route()->named('details')) {
            //
    }
return $next($request);
}


When we enter the route of the root directory, i.e., localhost/laravelproject/public/, the view of the Employee is appeared shown in the above screenshot that shows the link of the Employee . When we click on the Student link, then the new page appeared whose named route is Employee.details.

Related Post