Does Laravel allow us to add multiple Policies for a Model? I.e. consider App\Providers\ASuthServiceProvider
's $policies
property:
protected $policies = [
'App\Team' => 'App\Policies\TeamPolicy',
'App\Team' => 'App\Policies\RoundPolicy',
'App\Team' => 'App\Policies\AnotherPolicy',
];
I haven't tested it in an application, because even if it worked, I would be here asking a similar question, regarding whether this is considered bad practise or prone to unexpected behaviour.
The alternative I have is a very messy Policy, containing policies relating to several controllers, named in camel case:
/**
* Allows coach of Team and admin to see the Team management view.
* Used in TeamManagementController
*
* @param App\User $user
* @param App\Team $team
* @return boolean
*/
public function manage(User $user, Team $team)
{
return $user->id === $team->user_id || $user->isAdmin();
}
/**
* Allows a coach to detach themself from a Team.
* Used in TeamController
*
* @param App\User $user
* @param App\Team $team
* @return boolean
*/
public function detach(User $user, Team $team)
{
return $user->id === $team->user_id;
}
/**
* Below function are used for controllers other than TeamController and TeamManagementController.
* Reason: We need to authorize, based on a Team. Hence, using this Policy.
*/
/**
* Allows coach of Team, as well as admin to view players of a Team.
* Used in PlayerController
*
* @param App\User $user
* @param App\Team $team
* @return boolean
*/
public function indexPlayers(User $user, Team $team)
{
return $user->id === $team->user_id || $user->isAdmin();
}
/**
* Allows coach of Team, as well as admin to view players of a Team as an array.
* Used in PlayerController
*
* @param App\User $user
* @param App\Team $team
* @return boolean
*/
public function fetchPlayers(User $user, Team $team)
{
return $user->id === $team->user_id || $user->isAdmin();
}
etc. etc.
You could use traits to separate the logic for your policy.
You would create a base TeamPolicy
and then multiple traits with the various methods that you would want within the base class.
<?php
class TeamPolicy
{
use RoundPolicy, AnotherPolicy;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With