Generate URLs to Named Routes in Laravel
Laravel, Routing
Named routes in Laravel allow you to easily generate specific URLs. Referring to the named route throughout your project makes the codebase more robust. If a URL needs to be amended, this can be done easily by editing the route definition. Without named routes you’d need to amend all URL references to the amended route.
Routes generated by the Route::resource()
method will automatically have named routes assigned - taking the format resource.method
.
Manually Specify Named Routes
This is achieved by chaining the name()
method to the route definition:
Generate URLs to Named Routes
Laravel provides a global route()
function that gets the URL to a named route. The first Parameter is the route name (string). Depending on the route you’re trying to access you may also need to pass in an array of parameters as the second argument.
Simple example, as it would look as an anchor tag within in a Blade template:
…this generates a URL that links to posts/{id}
. For example: http://example.com/posts/10
.
The route()
function accepts three parameters:
- Route name (string)
- Parameters (mixed)
- Absolute (boolean, true by default)
You could make the URL relative by passing in false
as a third argument to the function:
…this generates: /posts/10
.
Adding Additional Parameters
The example above passes a single parameter ($id
) into the route
function. In this case, the ‘show’ method that is being hit expects a single argument - and this is correctly passed in. If more arguments are required (for example in the case of nested resources) they will be passed in the order specified in the route()
function.
Interestingly, Laravel is smart enough to know that additional parameters (beyond what is required by the accepting method) should be passed as GET parameters.
Example:
The generated URL looks like:
http://example.com/posts/1/comments/2?par=HELLO&par2=Goodbye
This might be handy of you were redirecting back to a page - you could use the amended GET parameters to alter elements of the page display.
Using Within Laravel Collective Forms
If your project requires the Laravel Collective Forms & HTML package, you can use named routes to set the form by passing an array to the Form::open()
method with with the key ‘route’:
The ‘route’ array is comprised of ‘route.name’ followed by route parameters.
Redirects
The Redirect::to()
method will also accept a named route:
comments powered by Disqus