How to check current URL in Laravel 5

How to check current URL in Laravel 5

When working with the web application, we often need to check if the current URL matches some conditions. To check current URL in blade or controller, laravel provides some helper functions which makes our work easier.

We can access current url using Laravel’s Request and URL facade. Here, we will access our url’s using different approaches in laravel 5.

Get full URL

This will give the complete url with the base url. We can get full url of active web address using the below syntax. Please note that this will get the url with parameters

Get current url

We can get the current url i.e. url after base url using the path() method.

Compate if current URL match certain pattern

This is really useful and often need a lot when working with the blade. Suppose, when we need to check if the URL is for displaying posts. So, the basic format of URL will be base-url/post/slug-of-each-post.

In such case, slug is unique for all post. So, we check pattern as /post/* to compare such conditions.

Note
The is() method accepts multiple arguments. So, you can write multiple conditions to check.

Get segment of current url

When we have to check for the segments of url, then segment function comes as a role play. Unlike to matching whole pattern, it checks for specific segment of url.

Get route name

We sometimes need to check the name of route rather than url itself. We can also get the route name using getName() function of route. The basic syntax for this is:

Note
This above Request::route()->getName() function is similar to Route::is('').

Get current url without parameters

We can get the url without parameters unlike fullUrl using current() method or url() method.

This is all for checking URL in laravel. If you find any problem in implementating the code, please don’t forget to drop a comment below.