Search

Laravel URL Helper Function: route

November 21, 2016 —John Koster

route($name, $parameters = [], $absolute = true, $route = null)

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.

Assuming the following named route:

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

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

1<?php
2 
3$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<?php
2 
3$url = route('profile', [
4 'custom' => 'data'
5]);

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<?php
2 
3// Fully qualified URL.
4$urlOne = route('profile', [
5 'custom' => 'data'
6]);
7 
8// Relative URL.
9$urlTwo = route('profile', [
10 'custom' => 'data'
11], 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.