-1

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);
    }
nowox
  • 25,978
  • 39
  • 143
  • 293

1 Answers1

-1
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.

Ankit Singh
  • 922
  • 9
  • 16
  • That's probably an anti-pattern, no matter how fine it works (or how the variable is called). I mean, the concept is the problem (as explained above), not necessarily the code. – Martin Zeitler Sep 21 '20 at 11:44
  • The `function index($me=false) {} ` is acceping the perameter. correct? Just access it. – Ankit Singh Sep 21 '20 at 11:47