fix: 🐛 update validation of associated tenants of users

This commit is contained in:
Alexis Gousseau 2025-05-28 15:58:50 +02:00
parent a978e6536c
commit 741d4be1bf
2 changed files with 20 additions and 17 deletions

View file

@ -6,6 +6,7 @@ use App\Enums\UserRolesEnum;
use App\Models\User;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\Rules\Enum;
@ -21,6 +22,20 @@ class StoreUserRequest extends FormRequest
return Gate::check('create', User::class);
}
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation(): void
{
if ($this->input('role') == UserRolesEnum::admin->value()) {
$this->merge([
'tenants' => null
]);
}
}
/**
* Get the validation rules that apply to the request.
*
@ -28,6 +43,7 @@ class StoreUserRequest extends FormRequest
*/
public function rules(): array
{
$isClient = $this->input('role') == UserRolesEnum::client->value();
return [
'first_name' => 'required|string|min:3|max:255',
'last_name' => 'required|string|min:3|max:255',
@ -37,9 +53,9 @@ class StoreUserRequest extends FormRequest
Rule::unique('users', 'email')
],
'role' => ['required', new Enum(UserRolesEnum::class)],
'tenants' => 'sometimes|nullable|array|min:1',
'tenants.*' => 'sometimes|nullable|array|min:1',
'tenants.*.id' => 'sometimes|nullable|exists:tenants,id',
'tenants' => $isClient ? 'required|array' : 'nullable|array',
'tenants.*' => $isClient ? 'required|array' : 'nullable|array',
'tenants.*.id' => $isClient ? 'required|exists:tenants,id' : 'nullable|exists:tenants,id',
];
}
@ -55,6 +71,7 @@ class StoreUserRequest extends FormRequest
'last_name' => trans('validation.attributes.last_name'),
'email' => trans('validation.attributes.email'),
'role' => trans('validation.attributes.role'),
'tenants' => Str::of(trans('models.classes.tenant'))->plural(),
];
}
}

View file

@ -18,20 +18,6 @@ class UpdateUserRequest extends StoreUserRequest
return Gate::check('update', $this->route('user'));
}
/**
* Prepare the data for validation.
*
* @return void
*/
protected function prepareForValidation(): void
{
$this->merge([
'tenants' => $this->route('user')->role->equals(UserRolesEnum::admin) ?
$this->input('tenants') :
$this->route('user')->tenants()->get(['id'])->toArray()
]);
}
/**
* Get the validation rules that apply to the request.
*