Skip to content

New: Uri pathSegments() helper method #55250

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Apr 2, 2025

Conversation

chester-sykes
Copy link
Contributor

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

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
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
Member

Nice - thanks. 👍

@taylorotwell taylorotwell merged commit 15ea7cf into laravel:12.x Apr 2, 2025
39 checks passed
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.

3 participants