0

I want to create a route using Laravel 8 that will allow for a number of multiple and optional parameters. For example, if this route was displaying a list of people, it could be something like any of the following:

  • /people
  • /people/age/24
  • /people/hair/brown/age/30
  • /people/status/4

Or if it's easier something like this:

  • /people
  • /people/age-24
  • /people/hair-brown/age-30
  • /people/status-4

The parameters are all optional. The order should not matter. If possible I would like to do this without the use of a controller.

Thanks!

1 Answer 1

1

You can use Encoded Forward Slashes. Using a where condition regular expression (.*):

# http://myapp.test/people/hair/brown/age/30

Route::get('people/{search?}', function ($search = null) {

    // Your logic here..

    dd($search); // hair/brown/age/30

})->where('search', '.*');

If you want to parse $search into an array that you might use to query your model, you can use this way:

Route::get('people/{search?}', function ($search = null) {

    $search = trim(preg_replace('|/?([^/]+)/([^/]+)|', '$1=$2&', $search), '&');
    parse_str($search, $query);
    $query = array_filter($query); // To prevent elements that have no value

    dd($query);

})->where('search', '.*');
  • /people/hair/brown/age/30
  • /people/hair/brown/age/30/key-with-no-value

Result :

[
  "hair" => "brown",
  "age"  => "24"
]
Sign up to request clarification or add additional context in comments.

3 Comments

I also don't recommend that you use the /people/hair-brown/age-30 format. Because it will be difficult to parse - if the key or value has -.
Awesome thanks @WahyuKristianto! I like this better than any solution I found before asking!
Glad to help you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.