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

前端 未结 6 719
滥情空心
滥情空心 2021-02-03 17:43

I have a url : http://localhost:8888/projects/oop/2

I want to access the first segment --> projects

I\'ve tried

6条回答
  •  悲&欢浪女
    2021-02-03 18:04

    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 be posts.

    //get segment 0
    $segment_users = request()->segment(0); //returns 'users'
    //get segment 1
    $segment_posts = request()->segment(1); //returns 'posts'
    

    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 the segment() method:

    public function index()
    {
        $prev_uri_segments = $this->prev_segments(url()->previous());
    }
    
     /**
     * 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 !== '';
        }));
    }
    

提交回复
热议问题