sveti petar
sveti petar

Reputation: 3797

Laravel policy not applying to model automatically

According to the Laravel docs, a policy should be auto-discovered if it follows naming conventions: it should be placed in the Policies directory, its name should be the model name plus the word Policy and the models should be in the app directory. This is all true in my case, but the policy isn't working.

The model name is Screen. The policy is named ScreenPolicy:

class ScreenPolicy
{
    use HandlesAuthorization;

    /**
     * Create a new policy instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    public function delete(User $user, Screen $screen)
    {
        return false;    //always return false for testing
    }
}

And in my controller, I have the following method that deletes a Screen:

public function delete(Request $request) {
    $screen = Screen::find($request->screen_id);
    $screen->delete();
    ...
}

My expectation is that I shouldn't be able to delete the Screen here since the policy always returns false, however the Screen is successfully deleted by calling this method. What am I doing wrong?

Upvotes: 1

Views: 914

Answers (1)

Digvijay
Digvijay

Reputation: 8967

You still need to call the authorize(). Check docs

$screen = Screen::find($id);
if ($this->authorize('delete', $screen)) {
   $screen->delete();
}

Upvotes: 2

Related Questions