Nerius Jok
Nerius Jok

Reputation: 3227

Laravel policy is not being called

I've created a policy with

php artisan make:policy AdvertisementPolicy --model=Advertisement

class AdvertisementPolicy
{
    use HandlesAuthorization;

    public function viewAny(User $user)
    {
        return false;
    }

    public function view(User $user, Advertisement $advertisement)
    {
        return false;
    }
}

I have manually registered the policy as well:

use App\Advertisement;
use App\Policies\AdvertisementPolicy;

class AuthServiceProvider extends ServiceProvider
{
    protected $policies = [
        Advertisement::class => AdvertisementPolicy::class,
        ...
    ];
}

But the policy is not being applied when I request the model view URLs. Are there any additional steps to fulfill this policy registration with Laravel? Is something missing from the documentation?

Upvotes: 2

Views: 1558

Answers (1)

nmfzone
nmfzone

Reputation: 2903

There is no something hidden in documentation. You just don't read the documentation carefully.

Please take a look at the Authorizing Actions Using Policies section.

Your policy is never called, because you don't use it anywhere in your code. Atleast, if you need to run your policy for your controller resources, you need to write something like this:

<?php

namespace App\Http\Controllers;

use App\Advertisement;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class AdvertisementController extends Controller
{
    public function __construct()
    {
        $this->authorizeResource(Advertisement::class, 'advertisement');
    }
}

Upvotes: 6

Related Questions