Q
Q
Quavo2020-06-13 12:29:20
Laravel
Quavo, 2020-06-13 12:29:20

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
}

But there were too many access checks, and I decided to refactor this logic. I created a middleware middleware "DocumentAccess"
It looks like this:
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);
        }
    }

How can I pass the Document model to it?

Route looks like this:
Route::get('documents/{document}', '[email protected]')->middleware('access');

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2020-06-13
@Quavo

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 question

Ask a Question

731 491 924 answers to any question