In this tutorial, you will learn how to check the current URL or route in your Laravel project. It is often necessary to check the current request URL in your controller to perform actions based on it. Therefore, understanding the method to determine the current URL or route is crucial for effective Laravel development.
I we will provide you with several examples of how to check the current requested URLs or routes in Laravel. This knowledge is particularly useful when working with menus or blade templates in Laravel projects. By understanding the different methods available to determine the current URL or route, you will have a better grasp of how to manipulate menus and templates in your Laravel application.
I assume that you already have Laravel project up and running if not you checkout this tutorial to setup new Laravel application.
Follow – Develop Exclusive Laravel 6 CRUD Application with Input Validations
Table of Contents
How to Get Current Request URL
Get current URL without the query string
echo \Request::url();
Or use global url function
echo url()->url();
Or use current function
echo url()->current();
Get current full url with query string parameters
echo url()->full();
Get previous URL in Laravel
Sometimes, we may need to check what the last requested or previous URL was. It is a simple process to do this in Laravel. Here’s how:
echo url()->previous();
Current URL is Equal to given String
To evaluate, hide, or show something depending on the request, we need to match the current URL to a given string. This can be done using the “is” function from the request facade.
if (request()->is('user-profile')) {
//
}
Current URL Contains given Pattern
We can also check url using particular pattern like if you want to check that url matches to certain pattern product/3939
Here is the example to achieve this using same request facade.
if (request()->is('product/*')) {
//
}
How to Get Route by Name
To check the name of the current route, you can use the Route class. This is especially useful when you do not want to manipulate the full URL or when your URL may change in the future.
\Route::current()->getName();
Match current route using route Name
As we saw in the previous step, we can route by its name. We can also easily check the current URL using the route name by simply doing the following:
if(\Route::current()->getName() == 'name-of-your-dsire-route')
{
}
window.setInterval(function(){
var v = document.getElementById(‘ab-message’);
if(v){ v.remove(); }
}, 1);