1

I am trying to create an API with Laravel 5.6, however, it seems to me that it's not possible to use optional route parameters before/after the parameter.

I'd like to achieve the following:

Route::get('api/lists/{id?}/items', 
[
    'as'    => 'api/lists/items/get', 
    'uses'  => 'ListsController@getListItems'
]);

With the above scenario, if I'm trying to visit api/lists/1/items it shows the page. On the other hand, if I'm trying to visit api/lists/items it says that the page is not found.

What I basically want is if there's no List ID specified, Laravel should fetch all the List ID's items, otherwise it should only fetch the specific ID's items.

Q: How is it possible to the optional parameter in between the 'route words'? Is it even possible? Or is there an alternative solution to this?

0

2 Answers 2

6

As far as I know, it's not possible to use optional parameters in the middle of your url.

You could try a workaround by allowing 0 for the optional parameter and loading all items in this case, as described here.

However, I'd recommend going with two different routes here to match everything you want:

api/lists/items
api/lists/{id?}/items
Sign up to request clarification or add additional context in comments.

Comments

3

You have to give default value for optional parameter in the controller:

Route

Route::get('api/lists/{id?}/items', 'ListsController@getListItems');

ListsController

public function getListItems($id = null) {
    ---your code----
}

Reference

2 Comments

This solution is not working because the route is not even found.
This is not the solution because first of all laravel needs to find the route and /api/lists/items does not match with any of routes so it goes to 404 page

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.