Home > OS >  How to take middleware on one function on route ressource (laravel)
How to take middleware on one function on route ressource (laravel)

Time:10-27

I want take auth middleware on only create, update, delete route ressource. I know how to do with simple route, so, i don't know with ressource route.


Route::resource('cars', CarController::class);
Route::get('/cars/{car}/delete', [CarController::class, 'softdelete'])->name('cars.softdelete')->middleware('auth');

Route::get('/dashboard', function () {
    return view('dashboard');
})->middleware(['auth'])->name('dashboard');

CodePudding user response:

You can put the middleware on your controller:

public function __construct()
{
        $this->middleware('auth')->except(['index','show']);
        // OR
        $this->middleware('auth')->only(['store','update','edit','create']);
}

CodePudding user response:

You can do that if you define the resource route with and without middleware separate: (quick example of the idea)

Route::resource('cars', CarController::class, [
        'only' => [
            'index',
            'show'
        ]
    ]);

Route::resource('cars', CarController::class, [
        'except' => [
            'index',
            'show'
        ]
    ])
    ->middleware([ 'auth']);
  • Related