Search code examples
phplaravellaravel-9laravel-middleware

How with Route::resource to apply middleware only to store/update?


I need to set DataSavingClearing middleware when data is stored/updated, like

Route::put('data-put', array('as' => 'data-put', 'uses' => 'Controller@update'))->middleware('DataSavingClearing:notes');

Parameter notes is some additive parameter for DataSavingClearing.

But my many routes are defined with resource

Route::resource('items', 'Controller', [ 'except' => ['show' ] ] );  // ->middleware('DataSavingClearing');

Can I set someway to show in line above that middleware DataSavingClearing must be applied only to store/update ?

laravel/framework 9.19

Thanks in advance!


Solution

  • You can add middleware for certain routes in the constructor of the controller like this:

    /**
     * Enforce middleware.
     */
    public function __construct()
    {
        $this->middleware('auth', ['only' => ['create', 'store', 'edit', 'delete']]);
        // Alternativly
        $this->middleware('auth', ['except' => ['index', 'show']]);
    }
    

    Documentation