Requests

Creation of a custom request

This is an example of a custom request to validate the parameters within it.

The parameters must have the same validation that is present in the database (if exists), for more info always check the official Laravel documentation.

class StoreUserRequest extends TranslationRequest
{
    protected $translationPath = 'cruds.user.fields.';

    public function authorize(): bool
    {
        return Gate::allows('user_create');
    }

    public function rules(): array
    {
        return [
            'name' => [
                'required'
            ],
            'surname' => [
                'required'
            ],
            'email' => [
                'required'
            ],
            'password' => [
                'nullable'
            ],
            'roles' => [
                'array',
                'required'
            ],
            'roles.*.id' => [
                'required'
            ],
        ];
    }
}

The peculiarity of the requests on Balance is that they can extend the class TranslationRequest, which makes the match between the parameters and the prameters translated in the translation files, thanks to the attribute $translationPath, so it allows us to avoid each time to define the translations of the attributes that makes this request automatically.

protected $translationPath = 'cruds.user.fields.';

This is the TranslationRequest class:

class TranslationRequest extends FormRequest
{

    public function attributes()
    {
        $attributes = [];
        foreach ($this->toArray() as $key => $value) {
            if (is_array($value)) {
                foreach ($value as $elementKey => $elementValue) {
                    $attributes[$key . '.' . $elementKey] = __($this->translationPath . $elementKey);
                }
            } else {
                $attributes[$key] = __($this->translationPath . $key);
            }
        }

        return $attributes;
    }
}

Last updated