xtremer360
2 months ago
563
16
Laravel

Adding Fields To Validated That Aren't Directly Validated

Posted 2 months ago by xtremer360

I'm running into a problem where I'm trying to send all the validated request data to the create method for an Eloquent model. I found a macro that can help send all validated data except for any fields that shouldn't be send to the create method. The problem here is that I can't do this because of the afterValidationHook method in my request class. The reason why I can't is because when it goes to create the model its going to look for the feet and inches parameters and those don't exist in the database table.

Does anyone have any suggestions on what I could do here so that I could easily pass validated data minus the feet and inches but plus the height parameter added in the hook?

Patient::create($request->validatedExcept('started_at'));
<?php

namespace App\Http\Requests\Patients;

use App\Models\Patient;
use Illuminate\Validation\Validator;
use Illuminate\Foundation\Http\FormRequest;

class StoreRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'feet' => [
                'required',
                'integer',
                'min:5',
                'max:7'
            ],
            'inches' => [
                'required',
                'integer',
                'max:11'
            ],
            'started_at' => [
                'nullable',
                'string',
                'date_format:Y-m-d H:i:s'
            ],
            // More validated fields
        ];
    }

    /**
     * Configure the validator instance.
     *
     * @param  \Illuminate\Validation\Validator  $validator
     * @return void
     */
    public function withValidator(Validator $validator): void
    {
        $validator->after(function (Validator $validator) {
            if ($validator->errors()->isEmpty()) {
                $this->merge(['height' => ($this->input('feet') * 12) + $this->input('inches')]);
                $this->offsetUnset('feet');
                $this->offsetUnset('inches');
            }
        });
    }
}

Request::macro('validatedExcept', function ($keys) {
    $keys = is_array($keys) ? $keys : func_get_args();

    $results = $this->validated();

    Arr::forget($results, $keys);

    return $results;
});

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