ella-stinnes's avatar

Policy viewAny

Both an administrator and company administrator should be able to access the companies.index page.

  • Administrator - should be able to list all companies.

  • Company Administrator - should only list the companies they are related to.

I've seen differing opinions on the policy viewAny method.

Should I be using this to define whether the user role can access the index page as I have below:

public function viewAny(User $user): bool
{
        return $user->isRole([UserRole::Administrator, UserRole::CompanyAdministrator]);
}

viewAny implies the CompanyAdministrator role can view any company.

Should I therefore be creating another method for allowing access to the index page (if so, what would you name this)?

0 likes
4 replies
Glukinho's avatar

Accessing a page and viewing a model are different authorization rules and should be handled differently: as a Gate and a Policy respectively.

But both Gate and Policy can check the same role/permission if your app logic implies it.

ella-stinnes's avatar

To check my understanding, I would define a gate for the page access as follows:

Gate::define('companies-index', function (User $user) {
        return $user->isRole([UserRole::Administrator, UserRole::CompanyAdministrator]);
    });

Then the policy would determine whether they can viewAny and/or view a specific model as follows?

A company administrator would not be able to viewany so a query scope would be applied to the index page query?

public function viewAny(User $user): bool
{
        return $user->isRole([UserRole::Administrator]);
}

public function view(User $user, Company $company): bool
{
		if ($user->isRole([UserRole::Administrator]))
            return true;
        
        if($user->isRole([UserRole::CompanyAdministrator])) {
            return $user->company_id === $company->id;

		return false;
}

Please or to participate in this conversation.