Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

php
laravel
communitycreator

How to work with URLs in Laravel

Chinweuba Elijah Azubuike

Introduction

In most applications, logs store all the events and actions of visitors and users, and the URL that the user accessed is one of the necessary pieces of information for that log.

In Laravel, it’s very easy to get this URL dynamically, as not all URLs are static in web applications. The current URL can also be used to create hyperlinks for your web application. We will be working with three methods, as shown below.

URL::current();;

URL::full();

URL::previous();

Method 1: URL::current()

The first method, URL::current();, returns the current URL without a query string. Let’s see an example by creating a route and returning the value of the URL::current();.

<?php

// app/routes.php

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

The code above will return a URL like this, http://yoursite.com/current/url, if you visited the corresponding route /current/url, without the query string.

Method 2: URL::full()

Let’s look at the URL::full(); method. This returns the URL alongside the query string.

<?php

// app/routes.php

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

  • Make a get request to check if a query string is returned.

  • Visit this URL in your application: /current/url?john=doe.

  • You will notice that it does not have the same return as URL:::current().

  • It returns http://yoursite.com/current/url?john=doe, which is the dynamism referred to earlier in the shot.

Method 3: URL::previous()

Lastly, let’s look at the URL::previous() method.

<?php

// app/routes.php

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

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

This method applies to cases when you set a redirect and you want to catch where the user was redirected from. The code above returns http://yoursite.com/first, because although the current route might be second, it was redirected from the first route.

RELATED TAGS

php
laravel
communitycreator

CONTRIBUTOR

Chinweuba Elijah Azubuike
RELATED COURSES

View all Courses

Keep Exploring