Get the last part of the current url in Laravel 5 using Blade

How to get the last part of the current unsigned url / , dynamically?

For instance:

At www.news.com/foo/bar get a bar .

Get fun www.news.com/foo/bar/fun .

Where to put the function or how to implement it in the current view?

+9
source share
8 answers

The route object is the source of the information you need. There are several ways in which you can get information, and most of them involve communicating something to your mind. I highly recommend not working inside the blade server, as these are controller actions.

Passing value to click

The easiest way is to make the last part of the route a parameter and pass this value to the view.

 // app/Http/routes.php Route::get('/test/{uri_tail}', function ($uri_tail) { return view('example')->with('uri_tail', $uri_tail); }); // resources/views/example.blade.php The last part of the route URI is <b>{{ $uri_tail }}</b>. 

Avoiding route options requires a bit more work.

 // app/Http/routes.php Route::get('/test/uri-tail', function (Illuminate\Http\Request $request) { $route = $request->route(); $uri_path = $route->getPath(); $uri_parts = explode('/', $uri_path); $uri_tail = end($uri_parts); return view('example2')->with('uri_tail', $uri_tail); }); // resources/views/example2.blade.php The last part of the route URI is <b>{{ $uri_tail }}</b>. 

Doing all this in the blade with request helper .

 // app/Http/routes.php Route::get('/test/uri-tail', function () { return view('example3'); }); // resources/views/example3.blade.php The last part of the route URI is <b>{{ array_slice(explode('/', request()->route()->getPath()), -1, 1) }}</b>. 
+8
source

Of course, there is always a Laravel way:

 request()->segment(count(request()->segments())) 
+27
source

Here is how I did it:

 {{ collect(request()->segments())->last() }} 
+10
source

Use basename() along with Request::path() .

 basename(request()->path()) 

You should be able to call it from anywhere in your code, since request() is a global helper function in Laravel, and basename() is a standard PHP function that is also available around the world.

+8
source

You can use the Laravel last helper function. Like this:

last(request()->segments())

+5
source

Try request()->segment($number) it should provide you with a URL segment.

In your example, this should probably be request()->segment(2) or request()->segment(3) based on the number of URL segments.

+4
source

It was useful to me:

 request()->path() 

from www.test.site/news

get → news

0
source

Try:

 {{ array_pop(explode('/',$_SERVER['REQUEST_URI'])) }} 

It should work well.

-1
source

All Articles