eComEvo
eComEvo

Reputation: 12551

Mutators don't work on mass inserts

If I have an array of values I want to do a mass insert on:

Item::insert([['price' => 1234.25], ['price' => 4321.75]]);

Then my mutators don't fire:

public function setPriceAttribute($value)
{
    $this->attributes['price'] = round($value, 2) * 100;
}

Unless I break each out into a create:

foreach ([['price' => 1234.25], ['price' => 4321.75]] as $new)
    Item::create($new);

Am I missing something here? Or will I have to manually apply round($value, 2) * 100 to each price value within the array?

I have a LOT of records to insert, so a mass insert is most efficient on the database.

Upvotes: 1

Views: 764

Answers (1)

Mike Barwick
Mike Barwick

Reputation: 5367

insert is db and create is eloquent. Use Item::create($new);, but it'd need to be in a foreach.

insert is not Eloquent, but can mass insert - but timestamp updating and the works won't be added, etc.

So foreach, might be your best bet here:

foreach ($news as $new)
{
    Item::create($new);
}

Seems either way you're going to need to do a foreach regardless. Either to mutate OR create the records. Pick your poison.

Upvotes: 1

Related Questions