How to get current url in Laravel

In blade files or Controllers, you may want to catch current url or path name. You may sometimes want to change CSS or need to change element based on current route. Laravel provides simple methods to get current urls or path.

Here is few examples you may use to get current route and url data. The methods will automatically use the schemes(http or https) from url.

Get current url without query string.

echo \URL::current() // or
echo url()->current()
// https://hackthestuff.com/article/

Get the full url with query string parameters.

echo \URL::full() // or
echo url()->full()
// https://hackthestuff.com/article?param=value&param2=value2

You may sometimes want to get previous url.

echo \URL::previous() // or
echo url()->previous()
// https://hackthestuff.com/article/

If you want to get specific segment of url, you may use segment() method with segment number as parameter. segment() will count number from 1. 

echo Request::segment(1) // or
echo request()->segment(1) // or
// article

If you want to get name of the route, you may use \Route::currentRouteName() method.

echo \Route::currentRouteName()
echo \Route::current()->getName()
// article.index

You may get the controller path and method name from \Route::currentRouteAction() method

echo \Route::currentRouteAction()
// App\Http\Controllers\ArticleController@index

You may get the route object with \Route::current() object for more details.

Tags: