Bios90
Bios90

Reputation: 811

Laravel update model with another model

I want to update one model in database with all fields except id from other model.

For example i have two models

Model1: {
    "id":1,
    "name":"Name1",
    "address":"Adress1",
    "phone":"1234567"
}

Model2: {
    "id":null,
    "name":"Name2",
    "address":null,
    "phone":"777777"
}

How can update model1 with model2 values, so that model1 would have this values (all values from model2 except id)

{
    "id":1,
    "name":"Name2",
    "address":null,
    "phone":"777777"
}

P.S. fill() method ignores null values, forceFill() uses nulls but also other fields from array for example attributed fields.

Upvotes: 0

Views: 3295

Answers (1)

mrhn
mrhn

Reputation: 18916

Utilize attributesToArray() and fill(). Properties need to be fillable.

$properties = array_only($model1->attributesToArray(), ['name', 'address', 'phone']);

$model2->fill($properties);

Upvotes: 2

Related Questions