Search

Laravel 5: Generating URLs to Named Routes With route

April 14, 2018 —John Koster

The route helper function can be used to generate URLs to a given named route. The route function defines four parameters, but only three are used internally ($name, $parameters and $absolute). It acts a shortcut to calling the "Illuminate\Routing\UrlGenerator::route" instance method.

The $name is the name of the route to generate the URL for. Extra data can be supplied using the $parameters array parameter that will be appended to the URL as a query string. The $absolute parameter can be used to indicate if a fully qualified or relative URL will be returned from the route helper function.

#Signature

The signature of the route function is:

1function route(
2 $name,
3 $parameters = [],
4 $absolute = true
5);

#Example Use

Assuming the following named route:

1Route::get('user/profile', [
2 'as' => 'profile',
3 function () {
4 return 'User profile route.';
5 }
6]);

We can generate a simple URL to it using the following example:

1$url = route('profile');

The resulting URL would be look like this (the actual URL returned will change depending on the route name and the domain name):

1http://laravel.artisan/user/profile

Additional data can be added to the resulting query string by supplying an argument for $parameters:

1$url = route('profile', [
2 'custom' => 'data'
3]);

The resulting URL would look something like this:

1http://laravel.artisan/user/profile?custom=data

By default the route helper function generates fully qualified URLs. To change this behavior, supply an argument with a truth value of false for the $absolute argument. The following example demonstrates the differences in calling the route function with different $absolute values:

1// Fully qualified URL.
2$urlOne = route('profile', [
3 'custom' => 'data'
4]);
5 
6// Relative URL.
7$urlTwo = route('profile', [
8 'custom' => 'data'
9], false);

The resulting URLs would be:

1Fully qualified URL.
2http://laravel.artisan/user/profile?custom=data
3
4Relative URL.
5/user/profile?custom=data

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.