Laravel, how cast object to new Eloquent Model? Laravel, how cast object to new Eloquent Model? laravel laravel

Laravel, how cast object to new Eloquent Model?


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.