w3resource

Laravel (5.7) URL Generation

Your web application revolves around routes and URLs. After all, they are what direct your users to your pages. At the end of the day, serving pages is what any web application must do.

Your users might not be interested in long if you are only serving one page, and if you intend to move them around your website or web application, then you will need to use a critical feature of the web called hyperlinks. In order to construct hyperlinks we need to build URLs to our application. We could do them by hand, but Laravel can save us some effort by providing a number of helpers to assist with the construction of URLs. Let's take a look at those features.

The current URL

Getting the current URL in Laravel is easy. Simply use the URL::current() helper. Let's create a simple route to test it.

<?php

// app/routes.php

Route::get('/current/url', function()
{
    return URL::current();
});

Now if we visit our /current/url url, we receive the following response.

http://myapp.dev/current/url

Let's have a look at URL::full() next, you see it returns the current URL.

Let's try that last route once more, but this time we will include some additional data as GET parameters.

http://myapp.dev/current/url?foo=bar

You will see that the result of URL::current() strips off the extra request data, like this:

http://myapp.dev/current/url

Well the URL::full() method is a little different. Let's modify our existing route to use it. Like this:

<?php

// app/routes.php

Route::get('/current/url', function()
{
    return URL::full();
});

Now let's try the /current/url?foo=bar URL again. This time we get the following result:

http://myapp.dev/current/url?foo=bar

You see, the URL::full() method also includes additional request data.

This next one isn't really a way of getting the current URL, but I feel that it certainly has its place in this subheading. You see, it's a method of getting the previous URL, as denoted by the 'referer' request header.

I have come up with a cunning trap using a Redirect response type to display the output. Take a look at the following example.

<?php

// app/routes.php

Route::get('first', function()
{
    // Redirect to the second route.
    return Redirect::to('second');
});

Route::get('second', function()
{
    return URL::previous();
});

So our first route redirects to the second route. The second route will output the URL of the previous request using the URL::previous() method.

Let's visit the /first URI to see what happens.

You might have seen the redirect notice displayed for a split second, but hopefully, you will have received the following response:

http://demo.dev/first

You see, after the redirect, the URL::previous method gives the URL for the previous request, which in this instance is the URL to the first route.

Generating Framework URLs

This section is all about generating URLs that will help us navigate around the different routes or pages of our site or application.

Let's start by generating URLs to specific URI's. We can do this using the URL::to() method. Like this:

<?php

// app/routes.php

Route::get('example', function()
{
    return URL::to('another/route');
});

The response we receive when we visit /example looks like this.

http://demo.dev/another/route

As you can see, Laravel has built a URL to the route we requested. You should note that the another/route doesn't exist, but we can link to it anyway. Make sure that you remember this when generating links to URIs.

You can specify additional parameters to the URL::to() method in the form of an array. These parameters will be appended to the end of the route. Here's an example:

<?php

// app/routes.php

Route::get('example', function()
{
    return URL::to('another/route', array('foo', 'bar'));
});

The resulting string will take the following form.

http://myapp.dev/another/route/foo/bar

If you want your generated URLs to use the HTTPS protocol, then you have two options. The first option is to pass true as the third parameter to the URL::to() method, like this:

URL::to('another/route', array('foo', 'bar'), true);

However, if you don't want to provide parameters to your URL, you will have to pass an empty array, or null as the second parameter. Instead, it's more effective to use the descriptive URL::secure() method, like this:

URL::secure('another/route');

Once again, you can pass an array of route parameters as the second method parameter to the URL::secure() method, like this:

URL::secure('another/route', array('foo', 'bar'));

Let's look at the next generation method. Do you remember that we discovered how to give our routes nicknames within the advanced routing chapter? Named routes look like this:

<?php

// app/routes.php

Route::get('the/best/avenger', array('as' => 'ironman', function()
{
    return 'Tony Stark';
}));

Route::get('example', function()
{
    return URL::route('ironman');
});

If we visit the /example route, we receive the following response.

http://myapp.dev/the/best/avenger

Laravel has taken our route nickname and found the associated URI. If we were to change the URI, the output would also change. This is very useful for avoiding having to change a single URI for many views.

Just like the URL::to() method, the URL::route() method can accept an array of parameters as the second method parameter. Not only that, but it will insert them in the correct order within the URI. Let's take a look at this in action.

<?php

// app/routes.php

Route::get('the/{first}/avenger/{second}', array(
    'as' => 'ironman',
    function($first, $second) {
        return "Tony Stark, the {$first} avenger {$second}.";
    }
));

Route::get('example', function()
{
    return URL::route('ironman', array('best', 'ever'));
});

If we visit the following URL...

http://myapp.dev/example

...Laravel will fill in the blanks in the correct order, with the parameters we have provided. The following URL has displayed a response.

http://myapp.dev/the/best/avenger/ever

There's one final routing method of this type that you need to know, and that's how to route to controller actions. In fact, this one should be pretty simple, since it follows the same pattern as the URL::route() method. Let's take a look at an example.

<?php

// app/routes.php

// Our Controller.
class Stark extends BaseController
{
    public function tony()
    {
        return 'You can count on me, to pleasure myself.';
    }
}

// Route to the Stark controller.
Route::get('i/am/iron/man', 'Stark@tony');

Route::get('example', function()
{
    return URL::action('Stark@tony');
});

In this example, we create a new controller called 'Stark' with a 'tony()' action. We create a new route for the controller action. Next we create an example route which returns the value of the URL::action() method. The first parameter of this method is the Class and action combination that we wish to retrieve the URL for. The format for this parameter is identical to that which we use for routing to controllers.

If we visit the /example URL, we receive the following response.

http://myapp.dev/i/am/iron/man

Laravel has identified the URL for the controller action pair that we requested and delivered it as a response. Just as with the other methods, we can supply an array of parameters as a second parameter to the URL::action() method. Let's see this in action.

<?php

// app/routes.php

// Our Controller.
class Stark extends BaseController
{
    public function tony($whatIsTony)
    {
        // ...
    }
}

// Route to the Stark controller.
Route::get('tony/the/{first}/genius', 'Stark@tony');

Route::get('example', function()
{
    return URL::action('Stark@tony', array('narcissist'));
});

Just as in the last example, we supply an array with a single parameter as a parameter to the URL::action() method, and Laravel constructs the URL to the controller, with the parameter in the correct location.

The URL that we receive looks like this.

http://myapp.dev/tony/the/narcissist/genius

Asset URLs

URLs to assets such as images, CSS files, and JavaScript need to be handled a little differently. Most of you will be using pretty URLs with Laravel. This is the act of rewriting the URL to remove the index.php front controller, and making our URLs more SEO friendly.

However, in some situations, you may not wish to use pretty URLs. However, if you were to try to link to an asset using the helpers mentioned in the previous subchapter, then the index.php portion of the URL would be included, and the asset links would break.

Even with pretty URLs, we don’t want to link to our assets using relative URLs because our routing segments will be confused for a folder structure.

Helpers are provided to generate absolute URLs for our assets. Let's take a look at some of these helpers.

First, we have the URL::asset() method, let's take a look at it in action. The first parameter to the method is the relative path to the asset.

<?php

// app/routes.php

Route::get('example', function()
{
    return URL::asset('img/logo.png');
});

Now, if we visit the URL /example then we are greeted with the following response.

http://myapp.dev/img/logo.png

Laravel has created an absolute asset path for us. If we want to use a secure HTTPS protocol to reference our assets, then we can pass true as a second parameter to the URL::asset() method, like this:

<?php

// app/routes.php

Route::get('example', function()
{
    return URL::asset('img/logo.png', true);
});

Now we receive the following response from the /example URL.

https://demo.dev/img/logo.png

Great! Laravel also provides a much more descriptive method of generating secure asset URLs. Simply use the URL::secureAsset() method and pass the relative path to your asset.

<?php

// app/routes.php

Route::get('example', function()
{
    return URL::secureAsset('img/logo.png');
});

The response from this route is the same as the previous method.

https://demo.dev/img/logo.png

Generation Shortcuts

However, it’s good practice for the logic in your views to be short and neat. Also, it takes some stress off your fingers.

This is why Laravel has provided some shortcuts to some of the methods available on the URL class.

First, we have the URL() function. It accepts identical parameters to the URL::to() method, so I won't cover them again. Here's an example of it in action.

<!-- app/views/example.blade.php -->

<a href="{{ url('my/route', array('foo', 'bar'), true) }}">My Route</a>

Now if we look at the link within the rendered view's source, we see the following.

<a href="https://demo.dev/my/route/foo/bar">My Route</a>

The URL has been created in the same manner as the URL::to() method. As before, there is also a shortcut method that can be used to generate a secure URL. It looks like this:

<!-- app/views/example.blade.php -->

<a href="{{ secure_url('my/route', array('foo', 'bar')) }}">My Route</a>

The secure_url() function accepts the same signature as the URL::secure() method. The first parameter is the route, and the second is an array of route parameters to be appended.

The route() function is a shortcut to the URL::route() method, and be used for generating URLs to named routes. It looks like this:

<!-- app/views/example.blade.php -->

<a href="{{ route('myroute') }}">My Route</a>

As you might have guessed, there is also a shortcut for the third method of route URL generation. The action() function can be used as a shortcut to the URL::action() method, and can be used to generate links to controller actions.

<!-- app/views/example.blade.php -->

<a href="{{ action('MyController@myAction') }}">My Link</a>

Just as with the URL::action() method, they can accept second and third parameters for route parameters and secure URL generation.

<!-- app/views/example.blade.php -->

<a href="{{ action('MyController@myAction', array('foo'), true) }}">My Link</a>

The shortcut to the URL::asset() method is the asset() function, and as with all the other shortcuts, it accepts identical function parameters. Here's an example:

<!-- app/views/example.blade.php -->

<img src="{{ asset('img/logo.png') }}" />

Likewise, the shortcut to URL::secureAsset() is the secure_asset() function. It looks like this:

<!-- app/views/example.blade.php -->

<img src="{{ secure_asset('img/logo.png') }}" />

Previous: Laravel (5.7) Views
Next: Laravel (5.7) Session



Follow us on Facebook and Twitter for latest update.