How to access URL segment(s) in blade in Laravel 5?

北战南征 提交于 2019-12-03 00:59:35
Aniket Singh

Try this

{{ Request::segment(1) }}
DoubleJ

The double curly brackets are processed via Blade -- not just plain PHP. This syntax basically echos the calculated value.

{{ Request::segment(1) }} 

Here is how one can do it via the global request helper function.

{{ request()->segment(1) }}

Note: request() returns the object of the Request class.

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 ie starts from 0 and are a section of the uri 
after the base url(hppt://example.com)*/
//assuming current url == http://example.com/users/posts/latest/
//get segment 0
$segment_users          = request()->segments(0);//returns 'users'
//get segment 1
$segment_posts          = request()->segments(1);//returns 'posts'

You may have noted that the segment(s) method only works with the current URL ( url()->current() ) so I did design a small method to work with previous URL too by cloning the segments() method:

    public function index()
    {
        ....
        $prev_uri_segments = $this->prev_segments(url()->previous());//array
    }

    /**
 * Get all of the segments for the previous uri.
 *
 * @return array
 */
public function prev_segments($uri)
{
    $segments = explode('/', str_replace(''.url('').'', '', $uri));

    return array_values(array_filter($segments, function ($value) {
        return $value !== '';
    }));
}

Here is code you can get url segment.

{{ Request::segment(1) }}

If you don't want the data to be escaped then use {!! !!} else use {{ }}.

{!! Request::segment(1) !!}

https://laravel.com/docs/4.2/requests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!