ldc-com-app-bo/app/Http/Requests/Bo/Users/StoreUserRequest.php

78 lines
2.2 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Http\Requests\Bo\Users;
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;
class StoreUserRequest extends FormRequest
{
/**
* Determine if the user is authorized to make this request.
*
* @return boolean
*/
public function authorize(): bool
{
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.
*
* @return array
*/
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',
'email' => [
'required',
'email:rfc,strict,dns,spoof,filter',
Rule::unique('users', 'email')
],
'role' => ['required', new Enum(UserRolesEnum::class)],
'tenants' => $isClient ? 'required|array' : 'nullable|array',
'tenants.*' => $isClient ? 'required|array' : 'nullable|array',
'tenants.*.id' => $isClient ? 'required|exists:tenants,id' : 'nullable|exists:tenants,id',
];
}
/**
* Get custom attributes for validator errors.
*
* @return array
*/
public function attributes(): array
{
return [
'first_name' => trans('validation.attributes.first_name'),
'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(),
];
}
}