Laravel 5: Generating URLs With url

April 14, 2018 —John Koster

The url helper function is a versatile function that can be used to generate a URL to a given path or return an instance of the configured "Illuminate\Contracts\Routing" "\UrlGenerator" implementation (by default this is an instance of "Illuminate\Routing\UrlGenerator"). The url function can be used to generate arbitrary URLs.

Calling the url function without any arguments returns (by default) an instance of "Illuminate\Routing\UrlGenerator". Using the url function in this way is effectively the same as using the "Illuminate\Support\Facades\Url" facade.

#Signature

The signature of the url function is:

1 
2function url();
3 
4function url(
5 $path = null,
6 $parameters = [],
7 $secure = null
8);

#Example Use

All of the method/function calls in the following example are equivalent:

1use Illuminate\Support\Facades\Url;
2 
3// Using the URL facade.
4Url::action('SomeController@someAction');
5 
6// Calling the action method on the URL Generator.
7url()->action('SomeController@someAction');
8 
9// Using the action helper function.
10action('SomeController@someAction');

If arguments are supplied to the url helper function, it will invoke the to method on the resolved URL Generator instance with all of the supplied arguments:

The following lines are equivalent:

1use Illuminate\Support\Facades\Url;
2 
3// Using the URL facade.
4Url::to('arbitraryUrl');
5 
6// Using the url helper function.
7url('arbitraryUrl');

both calls would result in the following URL:

1http://laravel.artisan/arbitraryUrl

You can also include router parameters in the generated URL by utilizing the $parameters parameter. The following function call:

1url('arbitraryUrl', ['someParameter']);

would result in the following URL being generated:

1http://laravel.artisan/arbitraryUrl/someParameter

#Generating Secure URLs

To generate secure URLs using the url helper function, supply an argument with the truth value of true to the $secure parameter. To generate secure URLs that do not require parameters simply supply an empty array [] as the argument for $parameters.

The following examples demonstrate both ways of generating secure URLs:

1url('arbitraryUrl', [], true)
2url('arbitraryUrl', ['someParameter'], true)
1https://laravel.artisan/arbitraryUrl
2https://laravel.artisan/arbitraryUrl/someParameter

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.