1 week ago

What is the best way to authorize a create policy depending on value of a field?

Posted 1 week ago by chrisan

Say we have a user manager. Super admins can do anything. Admins can only manage users of their company.

The admin can create a new user or new admin, but I only want them to create a new user if the new user is also set to a company they manage.

Right now I am running authorize on the store method after validation and before the model is created/saved

$this->authorize('create', [User::class, $validatedAttributes['company_id']]);

Which checks against this policy

public function create(User $user, int $company_id) {
  if (in_array($company_id, $user->companyIds())) {
    return Response::allow();
  else {
    return Response::deny('You are not allowed to manage this company');

Where it will fail if they maliciously try to alter the form and create a user in another company.

Am I headed down the right path or should I be looking at something else to use? It works... but it "felt" kinda weird so I wasn't sure if I'm following the "Laravel way"

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