Home » Php » php – Laravel excluding resourceful functions in a clean way

php – Laravel excluding resourceful functions in a clean way

Posted by: admin February 25, 2020 Leave a comment


Currently I have these 4 resourceful routes in my web.php file.

Route::resource('campaigns', 'CampaignController')->except(['show']);
Route::resource('users', 'UserController')->except(['show']);
Route::resource('models', 'ModelController')->except(['show']);
Route::resource('trims', 'TrimController')->except(['show']);

And I can’t help but wonder. Can’t I add something to the Route::resources function to make it behave this way? This because they all have one thing in common. They except() the show() method.

It want to have something like this. (This example does not work because resources() does not have an except() method.

    'campaigns' => 'CampaignController',
    'users' => 'UserController',
    'models' => 'ModelController',
    'trims' => 'TrimController'
How to&Answers:

You can write your own class that extends Illuminate\Routing\Route and implement your resources method like that:

namespace App\Extends;

class Route extends Illuminate\Routing\Route {

   public function resources($routes, array $excepts) {
     foreach ($routes as $key => $value){
         $this->resource($key, $value)->except($excepts);


After you will need to bind your class in your service provider like this:

public function register()
    $this->app->bind('Illuminate\Routing\Route', 'App\Extends\Route');

and call resources in web.php like that:

    'campaigns' => 'CampaignController',
    'users' => 'UserController',
    'models' => 'ModelController',
    'trims' => 'TrimController'
], ['show']);

[EDIT 1]

From laravel.com/docs/5.8/controllers#resource-controllers

You may register many resource controllers at once by passing an array to the resources method:

    'photos' => 'PhotoController',
    'posts' => 'PostController'

But I don’t know if you can call ->except(['show']) like that



If you talk about possibility then yes it’s possible as above answer mentioned but by default you can’t

Take a look at this file,


 * @method static \Illuminate\Routing\PendingResourceRegistration resource(string $name, string $controller, array $options = [])
 * @method static void resources(array $resources)