4
votes

I'm using a Policy Class to authorize some users(authors or admins) to update and delete records from Post Model. It is a simple CRUD. The question is: How can I make a policy check run for specifics methods at once? For example, I can use a middleware in my PostController constructor to check if user is logged, but how can I do something similar to a policy that needs parameters?

PostController

public function __construct()
{
  $this->middleware('auth', ['except' => ['index', 'show']]);
}

PostPolicy

class PostPolicy
{
  use HandlesAuthorization;

  public function before($user)
  {
    if ($user->hasRole('admin')) {
      return true;
    }
  }

  public function manage($user, $post)
  {
    return $user->id == $post->user_id;
  }
}

AuthServiceProvider

public function boot()
{
  $this->registerPolicies();

  Gate::define('manage-post', 'App\Policies\PostPolicy@manage');
}

I tried this:

$this->middleware('can:manage-post', ['except' => ['index', 'show']]);

But it didn't work.

Thanks in advance.

1
need to see your route definitionlagbox

1 Answers

0
votes

I would just register the policy and use that instead of writing out an 'ability' separately.

can:manage,post

manage the action, post the Route Parameter to use for the gate (resource).

Laravel 5.5 Docs - Authorization - Authorizing Actions - via Middleware