I have a url : http://localhost:8888/projects/oop/2
I want to access the first segment --> projects
I've tried
<?php echo $segment1 = Request::segment(1); ?>
I see nothing print out in my view when I refresh my page.
Any helps / suggestions will be much appreciated
Here is how one can do it via the global
request
helper function.{{ request()->segment(1) }}
Note:
request()
returns the object of theRequest
class.Here is code you can get url segment.
If you don't want the data to be escaped then use {!! !!} else use {{ }}.
https://laravel.com/docs/4.2/requests
The double curly brackets are processed via Blade -- not just plain PHP. This syntax basically echos the calculated value.
Try this
BASED ON LARAVEL 5.7 & ABOVE
To get all segments of current URL:
$current_uri = request()->segments();
To get segment
posts
from http://example.com/users/posts/latest/NOTE: Segments are an array that starts at index 0. The first element of array starts after the TLD part of the url. So in the above url, segment(0) will be
users
and segment(1) will beposts
.You may have noted that the segment method only works with the current URL (
url()->current()
). So I designed a method to work with previous URL too by cloning thesegment()
method: