Home > Software design >  How with Route::resource to apply middleware only to store/update?
How with Route::resource to apply middleware only to store/update?

Time:09-01

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!

CodePudding user response:

You can set it in your controller's constructor:

class Controller
{
    public function __construct()
    {
        $this->middleware('DataSavingClearing:notes')->except('show');
    }
}

Or the other way round:

class Controller
{
    public function __construct()
    {
        $this->middleware('DataSavingClearing:notes')->only('store', 'update');
    }
}

CodePudding user response:

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

  • Related