I have a Laravel controller with destroying method and middleware with name CheckRole.
public function destroy(Request $request, $id)
{
// code to delete item
}
I am unable to use the $id in middleware CheckRole.
class CheckRole
{
public function handle($request, Closure $next)
{
}
}
And
$request->id and
$request->route('id')
are also not working with the middleware. How to fix this?
The $id
in the destroy function is the id
of the resource you want to delete, so that will never be the authenticated user id a better option for checking the role might be an authorization policy instead of a middleware.
Or get the authenticated user id by using: auth()->id()
or $request->user()->id
You can also add a method in your User
model, and check like that for example:
class User ...
public function isAdmin()
{
return $this->role === 'admin';
}
In the middleware
$request->user()->isAdmin();
--- EDIT
So if you use a resource
when you defined your route for example:
Route::resource('user', 'UsersController');
Then in your middleware you can access the id
of the user like this:
$request->user
If your route is like this:
Route::delete('/users/{user}', 'UsersController@destroy');
Then again you can get it using the named parameter $request->user
. Make sure that whatever you use on your route in the {}
that's the name of the parameter you use to get the id
from.