I get via Request a Json Object. I clearly parse this object in order to check if it may fit the destination model.
Instead of assigning property by property. Is there a quick way to populate the model with the incoming object?
If you have an array of arrays, then you can use the hydrate()
method to cast it to a collection of the specified model:
$records = json_decode($apiResult, true);
SomeModel::hydrate($records);
If you just have a single record, then you can just pass that array to the model’s constructor:
$model = new SomeModel($record);
Just pass your object casted to array as Model constructor argument
$model = new Model((array) $object);
Internally this uses fill()
method, so you may first need to add incoming attributes to $fillable
property or first create model and then use forceFill()
.
You should convert that object to array and use fill($attributes)
method.
As method name says, it will fill object with provided values. Keep in mind that it will not persist to database, You have to fire save()
method after that.
Or if You want to fill and persist in one method - there is create($attributes)
which runs fill($attributes)
and save()
under the hood.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With