Skip to content

New: Uri pathSegments() helper method#55250

Merged
taylorotwell merged 6 commits into
laravel:12.xfrom
chester-sykes:new/uri-path-segments
Apr 2, 2025
Merged

New: Uri pathSegments() helper method#55250
taylorotwell merged 6 commits into
laravel:12.xfrom
chester-sykes:new/uri-path-segments

Conversation

@chester-sykes

@chester-sykes chester-sykes commented Apr 2, 2025

Copy link
Copy Markdown
Contributor

Recently I ran into a situation where I needed the first path segment from an url, so I have added pathSegments() helper method to the Uri class to easily access them.

Calling pathSegments() on the Uri class will return an colleciton of all path segments then you can easily access any of them.

So instead of doing something like this:

        $path = Uri::of('https://laravel.com/one/two/three')->path();
        
        $firstSegment = collect(explode('/', $path))->first();
        // result: 'one'

You could just do this:

        $firstSegment = Uri::of('https://laravel.com/one/two/three')->pathSegments()->first();
        // result: 'one'

I think that this would be a handy to have if you are dealing with path segments. It doesn't break any existing features as it's a new method.

@shaedrich

Copy link
Copy Markdown
Contributor

I wonder if (not necessarily in this PR though) path() should return a custom collection (or Arrayable/ArrayAccess or the like) similar to UriQueryString that would

  • __toString() by internally calling implode() with / as glue
  • allowing to access and modify path segments by numeric index as well as name, in case we allow uri templates with Uri
  • etc.

@taylorotwell

Copy link
Copy Markdown
Member

Nice - thanks. 👍

@hivokas

hivokas commented Dec 14, 2025

Copy link
Copy Markdown
Contributor

Awesome addition 👍🏻 Just discovered it!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants