Answer the question
In order to leave comments, you need to log in
How to correctly pass parameter to laravel middleware?
Hello, I will describe the task: the application has some resource, say Document, this resource has certain access levels, 0 - for everyone, 1 - only for those users who are added to the participants of this resource.
Initially the code looked like this:
public function show(Document $document)
{
if(!$document->userHasAccess(auth()->user())
{
return permissionDenied();
}
return $document
}
class DocumentAccess
{
public function handle($request, Closure $next, Document $document)
{
if(!$document->userHasAccess($request->user()))
{
return response()->json(['error' => 'Permission denied'], 403);
}
return $next($request);
}
}
Route::get('documents/{document}', '[email protected]')->middleware('access');
Answer the question
In order to leave comments, you need to log in
Instead of userHasAccess, there is already a can method. Those. this bike is not needed. The models already have a lot of things to load them with their own authorization methods. For such purposes, Laravel has policies . No need to get models in middleware. It is called by one line of code in the controller and automatically returns 403.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question