Faraz Ali Faraz Ali - 1 month ago 19
PHP Question

Laravel Controller Middleware for Resources

I am trying to use a middleware on a resource route.

My Route ->

Route::resource('posts', 'PostController');


My Middleware ->

$user = Auth::user();

if(Auth::check()) {
if($user->is_admin) {
return $next($request);
} else {
return redirect()->route('home');
}
} else {
return redirect()->route('login');
}


My Controller Constructor ->

$this->middleware('auth');
$this->middleware('admin')->only('posts.destroy');


My Goal is to let only administrators destroy the post and not others.

But when I use
php artisan route:list
, the middleware shown are web,auth.

What am I doing wrong here?

Answer

You can try it as:

$this->middleware('admin')->only('destroy');

Docs

Comments