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