boneskhv
boneskhv

Reputation: 216

Different middleware for resource route

I have a resource controller and a route:

Route::resource('/path', Controller::class)

For each method of this controller I need to use different middleware. Can I do it inside route file, not in __construct() method?

I need something like that

Route::resource('/path', Controller::class)->middleware(['index' => 'guest', 'create' => 'auth'])

Upvotes: 1

Views: 992

Answers (2)

Othmane Nemli
Othmane Nemli

Reputation: 1193

Controller Middleware

class UserController extends Controller
{
    /**
     * Instantiate a new controller instance.
     *
     * @return void
     */
    public function __construct()
    {
        $this->middleware('auth');
        $this->middleware('log')->only('index');
        $this->middleware('subscribed')->except('store');
    }
}

Upvotes: 0

Obzi
Obzi

Reputation: 2390

You need to define each routes individually.

Route::resource('/path', Controller::class);

Is similar to :

Route::get('/path', [Controller::class, 'index'])->name('path.index');
Route::get('/path/create', [Controller::class, 'create'])->name('path.create');
Route::post('/path', [Controller::class, 'store'])->name('path.store');
Route::get('/path/{path}', [Controller::class, 'show'])->name('path.show');
Route::get('/path/{path}/edit', [Controller::class, 'edit'])->name('path.edit');
Route::put('/path/{path}', [Controller::class, 'update'])->name('path.update');
Route::delete('/path/{path}', [Controller::class, 'destroy'])->name('path.destroy');

With second route definition, you can add your middlewares.
So :

Route::middleware('guest')->group(function () {
    Route::get('/path', [Controller::class, 'index'])->name('path.index');
    Route::get('/path/{path}', [Controller::class, 'show'])->name('path.show');
});
Route::middleware('auth')->group(function () {
    Route::get('/path/create', [Controller::class, 'create'])->name('path.create');
    Route::post('/path', [Controller::class, 'store'])->name('path.store');
    Route::get('/path/{path}/edit', [Controller::class, 'edit'])->name('path.edit');
    Route::put('/path/{path}', [Controller::class, 'update'])->name('path.update');
    Route::delete('/path/{path}', [Controller::class, 'destroy'])->name('path.destroy');
});

Upvotes: 1

Related Questions