Laravel Gate method not being called

Viewed 2320

In my Laravel 5.4 application users can create Projects and then Posts inside those projects.

I'm trying to prevent users from creating or editing posts inside a project they don't have access to. To do this I implemented a Gate as explained here: https://laravel.com/docs/5.4/authorization#gates The gate checks if a user is the owner of the project.

Gate::define('create-post', function ($user, $project) {
    Log::info($project) // !!! Never gets called
    return $project->owner_id == $user->id;
});

On the PostController I call Gate::denies passing the project as an argument

if (Gate::denies('create-post', $project)) {
    abort(403);
}

The problem is the code I defined for the gate never gets called. Instead it always returns false and goes to the 403 error. However, the code does get called if I don't pass the project as an argument but that makes it useless.

I also want to add that in this case I cannot use a Policy because the create method only takes one argument ($user) and if I try to pass the $project it fails the same way it does with the Gate.

Is this a bug? Is there another, better way to implement this funcionality? Thanks.

4 Answers

I had the same issue. I replaced Gate::denies() with Gate::allows(). I'm not sure why but this worked for me. The policy framework is a little bit tricky to be honest

first, check to log in to your project then gate work because of the gate when work that you log in to your project.

Related