6 months ago

Are wildcard policies possible in Laravel?

Posted 6 months ago by TuffRivers

I want Clients and Admins to use the same controllers. Clients can only edit update delete controller actions where user->client_id = $model->client_id, and admins can edit/see/delete all.

I have tested a policy for one of my resources and it works. But I soon realized, 10/12 controllers require the exact same policy ruies. Can i create a wild card policy that would operate like this? How can i pass a "variable" model into the policy checks though? Is Model $model actually something that works or is that just pseudo code lol.

protected $policies = [
    Model1::class => WildcardPolicy::class,
    Model2::class => WildcardPolicy::class,
    Model3::class => WildcardPolicy::class,



namespace App\Policies;

use Illuminate\Auth\Access\HandlesAuthorization;
use Illuminate\Support\Facades\Auth;

class WildcardPolicy
    use HandlesAuthorization;

    public function __construct()
        $this->user = Auth::user();
    public function index(User $user)
        return $this->user->role === 'admin';
 								   Could be Card $card, Client $client, etc
    public function update(User $user, Model $model) //i have many models, how can i pass in model dynamically?
        return $this->user->client_id === $model->client_id;

Please sign in or create an account to participate in this conversation.