WildBill
WildBill

Reputation: 9291

How to create optional REST parameter in Laravel

I'd like my API to handle calls of the such:

/teams/colors /teams/1/colors

The first would return all colors of all teams, the second would return colors of team 1 only.

How would I write a route rule for this in Laravel?

Upvotes: 1

Views: 927

Answers (2)

The Alpha
The Alpha

Reputation: 146201

You may try something like this:

class TeamsController extends BaseController {

    // GET : http://example.com/teams
    public  function getIndex()
    {
        dd('Colors of all teams');
    }

    // GET : http://example.com/teams/1/colors
    public  function getColorsById($id)
    {
        dd("Colors of team $id");
    }

    // This method will call the "getColorsById" method
    public  function missingMethod($parameter = array())
    {
        if(count($parameter) == 2) {
            return call_user_func_array(array($this, 'getColorsById'), $parameter);
        }
        // You may throw not found exception
    }
}

Declare a single route for both methods:

Route::controller('/teams', 'TeamsController');

Upvotes: 0

Joe
Joe

Reputation: 1394

This should be simple using a laravel route.

Route::pattern('teamid', '[0-9]+');

Route::get('/teams/{teamid}/colors', 'controller@method');
Route::get('/teams/colors', 'controller@method');

Using the pattern, it lets you specify that a route variable must match a specific pattern. This would be possible without the pattern also.

I noticed you mentioned REST in the title. Note that my response is not using Laravel's restful routes system, but its normal routes system, but I'm sure this could be adapted to be restul, or work with the restful system.

Hope this helps.

Edit:

After a bit of looking around, you may be able to use this if you are using Route::resource or Route::controller.

Route::resource('teams', 'TeamsController');
Route::any('teams/{teamid}/colors', 'TeamsController@Method');

// Or to use a different route for post, get and so on.
Route::get('teams/{teamid}/colors', 'TeamsController@getMethod');
Route::post('teams/{teamid}/colors', 'TeamsController@postMethod');

Note: the resource word above can be replaced with ::controller. *Note 2: I have not tested this and am unable to guarantee it would work, but it does seem possible.*

Upvotes: 2

Related Questions