Skip to content
Advertisement

Laravel Update model automatically with Validator Data?

I was wondering if it was possible to update/save a model with the validator data? I’ve tried googling and can’t seem to find anything.

I’m just trying to do something like this

    $validator = Validator::make(request()->all(), [
        'first_name' => ['required', 'string', 'max:255'],
        'last_name' => ['required', 'string', 'max:255'],
        'address_line_1' => ['required', 'string', 'max:255'],
        'address_line_2' => ['required', 'string', 'max:255'],
        'postcode' => ['required', 'string', 'max:255'],
        'city' => ['required', 'string', 'max:255'],
        'county' => ['required', 'string', 'max:255'],
    ]);

    $address = $validator->getData();
    $address->save();

rather then having to set all the variables one by one and then saving?

Advertisement

Answer

Since getData() returns an associative array, you can use the update method:

$validator = Validator::make(request()->all(), [
    'first_name' => ['required', 'string', 'max:255'],
    'last_name' => ['required', 'string', 'max:255'],
    'address_line_1' => ['required', 'string', 'max:255'],
    'address_line_2' => ['required', 'string', 'max:255'],
    'postcode' => ['required', 'string', 'max:255'],
    'city' => ['required', 'string', 'max:255'],
    'county' => ['required', 'string', 'max:255'],
]);

$address->update($validator->getData());

Or (in my opinion), you can make use od the validate method of request that returns the validated data (if validation is successful)

$address->update(request()->validate([
    'first_name' => ['required', 'string', 'max:255'],
    'last_name' => ['required', 'string', 'max:255'],
    'address_line_1' => ['required', 'string', 'max:255'],
    'address_line_2' => ['required', 'string', 'max:255'],
    'postcode' => ['required', 'string', 'max:255'],
    'city' => ['required', 'string', 'max:255'],
    'county' => ['required', 'string', 'max:255'],
]));

Be aware that (depending on which version of Laravel are you using) in order to perform those types of operations, you might have to disable guard for those fields in the Model:

class ... extends Model{
     protected $guarded = [];
     // or
     protected $fillable = [/*list of attributes*/]
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement