'How to get last part of url in blade file (HTML) using laravel 5.2?
I am new to laravel. I want to get the last part of my url in the blade file(HTML file). I have done this one using php functionality . Is there any way I can get it using any laravel functionality .
Below is my code ,its working fine
<?php
$url = url()->current();
echo $end = end((explode('/', $url)));
?>
I have also used this one to get
Request::segment(2)
Here my url is http://localhost/blog/public/user/add-user. I want to get add-user in the html file.
Thank you
Solution 1:[1]
Try this code for getting last value of URL
$uri_path = $_SERVER['REQUEST_URI'];
$uri_parts = explode('/', $uri_path);
$request_url = end($uri_parts);
Solution 2:[2]
The answer to your question is: "No there is not any Laravel functionality" or more precisely Laravel helpers for getting the last segment, but fortunately you can just use php. The end has been mentioned and end works on an array, but I don't think it is possible to use directly on Request::segments(). That means you have to put Request::segments() into a variable (like $lastSegment) first and then use end on the variable.
The best and slimmest way I could find to do this is:
{{ basename(Request::url()) }}
Use this in blade, but of course like mentioned before you can add this in the controller or a Laravel view composer.
Solution 3:[3]
{{last(request()->segments())}}
Solution 4:[4]
If you specifically want the last segment (it may be the 2nd, 3rd, 4th etc) you can use end(Request::segments()) to conistently always get the last segment.
Also, if you don't want to call functions in your templates and be a bit more 'Laravel' why not bind it to your view from the controller?
In your controller:
public function show()
{
return view('your.view')->with('lastSegment', end(Request::segments()));
}
Then in your view you can do this:
<p> The last segment is {{$lastSegment}} </p>
Also, if you want to have $lastSegment be available in all your views without having to code it in all your controllers, look into using Laravel's view composer. Very powerful for making templates.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | smartrahat |
| Solution 2 | insitderp |
| Solution 3 | Syed Ali |
| Solution 4 |
