Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they’re what direct our users to our pages. At the end of the day, serving pages is what any web application should do.

Our users may not be all for long if we’re only serving one web page, and when you intend to move them around our web site or web application, then we might want to use a critical feature of the web called hyperlinks. In order to assemble hyperlinks we have to build URLs to our application. We might do them by hand, however Laravel can save us some effort by offering various helpers to help with the development of URLs. Let’s check out these options.

The current URL

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

<?php

// routes/web.php

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

Now if we go to our /current/url url, we obtain the following response.

http://myapp.dev/current/url

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

Let’s try that last route as soon as extra, however this time we are going to include some extra data as GET parameters.

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

You will see that the results of URL::current() strips off the additional request data, like this:http://myapp.dev/current/url

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

<?php

// routes/web.php

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

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

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

You see, the URL::full() methodology additionally contains additional request data.

This next one is not actually a method of getting the current URL, however I really feel that it actually has its place on this subheading. You see, it is a method of getting the previous URL, as denoted by the ‘referer’ request header.

I’ve give you a crafty trap using a Redirect response type to show the output. Take a have a look at the following example.

<?php

// routes/web.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 go to the /first URI to see what happens.

You may need seen the redirect discover displayed for a split second, however hopefully, you should have received the next response: http://demo.dev/first

You see, after the redirect, the URL::previous method provides the URL for the previous request, which on this occasion is the URL to the primary route.

Generating Framework URLs

This section is all about producing URLs that can assist us navigate across the completely different routes or pages of our website or application.

Let’s begin by generating URLs to particular URI’s. We can do that using the URL::to() method. Like this:

<?php

// routes/web.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

// routes/web.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

// routes/web.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

// routes/web.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


// 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

// routes/web.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

// routes/web.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

// routes/web.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

// routes/web.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') }}" />

LEAVE A REPLY

Please enter your comment!
Please enter your name here

564FansLike

Related Articles

Concept of Session in Laravel Tutorial

Sessions are used to store details about the user throughout the requests. Laravel supplies various drivers like file, cookie, apc, array, Memcached, Redis, and database to handle session data. By default, file driver is used as a result of it's light-weight....

Laravel Url Generation Tutorial

Our web application revolves around routes and URLs. After all, they're what direct our users to our pages. At the end of the day, serving pages is what any web application should do. Our users may...

Concept of Laravel Views Tutorial

In MVC framework, the letter "V" stands for Views. It separates the application logic and presentation logic. Views are saved in resources/views listing. Generally, the view contains the HTML which might be served by the application.
WP2Social Auto Publish Powered By : XYZScripts.com