Resource Controllers for API: How to Remove create/edit methods?

Resource controllers are great for CRUDs, but if we use them for APIs, there are two unnecessary methods – create() and edit(), cause there are no visual forms for it. So how to remove them from routes? There are two ways.

First: did you know that you can add another parameter to Route::resource()? Like this:

Route::resource('roles', 'RolesController', ['except' => ['edit', 'create']]);

So, just list the methods you won’t use. Or, alternatively, list methods you only want to use:

Route::resource('roles', 'RolesController', [
  'only' => ['index', 'show', 'store', 'update', 'destroy']
]);

Second: From Laravel 5.4.24 we have a new route function apiResource()

Route::apiResource('roles', 'RolesController');

It will form and pass the same only parameter as in example above.

Thanks Lasse Rafn for pointing it out on Twitter.

Like our articles?
Check out our Laravel online courses!

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here