Member-only story
Laravel: How I fixed having one Policy for each Auth Guard
There is something called “manually resolving policy names”
The authorization layer in Laravel, what you would commonly know as “the Gate”, commits one single sin, and it’s having one Policy for each Model.
While having one Policy for a Model is not a problem when your application authentication layer only works with a single authenticatable user, as it would be with the default App\Models\User Eloquent Model, it is when you start to add other guards like App\Models\Admin and App\Models\Coordinator to the equation. As you guess, you will have to manage each authenticated user type on the same method, and that can become hectic.
use App\Models\User;
use App\Models\Admin;
use App\Models\Coordinator;
use App\Models\Process;
public function update(User|Admin|Coordinator $user, Process $process)
{
if ($user instanceof User) {
// ...
}
if ($user instanceof Admin) {
// ...
}
if ($user instanceof Coordinator) {
// ...
}
}The policy becomes not responsable of managing one type of authenticated user, but many, and it can be really daunting to make a single Policy with multiple responsibilities for each authentication guard you have. Two can be bearable to some extent, but three or four and…
