same model policy: multiple resources

basically im using the same model in multiple resources, issue i have when using policies is that i can't find a way to get the resource is trying to access the policy to apply the correct filter... i'm talking something like this: https://github.com/filamentphp/filament/discussions/7928#discussioncomment-6773578
8 Replies
developer
developerOP6mo ago
i think im using the authorizeAccess for now ☑️
No description
developer
developerOP6mo ago
anyways, I think a centralized policy for all scenarios would be more effective than using authorizeAccess everywhere
Expecto Patronum
How to you set in the policy? Do you call User only or with Model that u using?
Gandalf
Gandalf6mo ago
You can extend the policy to create new policies. That's what I do when I've to use polymorphism. Allows me to customize the policy for specific cases.
Expecto Patronum
Can you show example in your policy file?
developer
developerOP6mo ago
no no, Im using that method directly in the resource page not in policy btw I'm not using Policies anymore 😶‍🌫️
Expecto Patronum
i see but can you show me how to do set in authorizeAccess ? because im also using multiple resource for 1 model . having an issue to set policy on them
Gandalf
Gandalf6mo ago
I think this question was for me. Here is a sample:
abstract class ModelPolicy
{
public static ?string $slug = 'models';

/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return $user->hasPermission(static::$slug . '.index');
}

/**
* Determine whether the user can view the model.
*/
public function view(User $user, Model $model): bool
{
return $user->hasPermission(static::$slug . '.show');
}
abstract class ModelPolicy
{
public static ?string $slug = 'models';

/**
* Determine whether the user can view any models.
*/
public function viewAny(User $user): bool
{
return $user->hasPermission(static::$slug . '.index');
}

/**
* Determine whether the user can view the model.
*/
public function view(User $user, Model $model): bool
{
return $user->hasPermission(static::$slug . '.show');
}
and then,
class AccountPolicy extends ModelPolicy
{
public static ?string $slug = 'accounts';

public function setOpeningBalance(User $user): bool
{
return $user->hasPermission('accounts.set-opening-balance');
}
}
class AccountPolicy extends ModelPolicy
{
public static ?string $slug = 'accounts';

public function setOpeningBalance(User $user): bool
{
return $user->hasPermission('accounts.set-opening-balance');
}
}
Here AccountPolicy has inherited all the methods from ModelPolicy with appropriate customizations through static variables. And custom policy method or overrides are specified in the derived policy, such as setOpeningBalance in this case.
Want results from more Discord servers?
Add your server