Search code examples
phplaravellaravel-controller

Call a controller with a parameter?


Let's imagine I have two Models:

  1. A list of users User
  2. A list of marbles Marble which belongs to one User

I would like to fetch all the existing marbles with api/marbles and only my marbles with api/user/marbles. The idea is to avoid a route named like api/marbles?owned=true

In my API routes I have this:

Route::get('marbles', 'MarbleController@index');
Route::get('user/marbles', 'MarbleController@index(true)');

Then in my MarbleController:

class MarbleControllerextends Controller
{
    function index($owned = false) {
        return $owned ? Marble::where('user_id', Auth::id())->get() : Marble::all();
    }
}

Unfortunately the MarbleController@index(true) doesn't really work because (true) will not be accepted by Laravel not populate the optional $owned variable.

Is there a way to avoid defining a new method such as Route::get('user/marbles', 'MarbleController@owned');

    function owned() {
        return $this->index(true);
    }

Solution

  • Route::get('marbles/{me?}', 'MarbleController@index'); will work fine.
    

    Here me is an optional parameter. If you omit it, it will take false otherwise true as it's value.