Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel, how cast object to new Eloquent Model?

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?

like image 308
koalaok Avatar asked Nov 10 '16 12:11

koalaok


3 Answers

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);
like image 52
Martin Bean Avatar answered Nov 03 '22 06:11

Martin Bean


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().

like image 4
Paul Avatar answered Nov 03 '22 06:11

Paul


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.

like image 1
Giedrius Kiršys Avatar answered Nov 03 '22 08:11

Giedrius Kiršys