Wistar
Wistar

Reputation: 3790

Laravel Eloquent ORM save: update vs create

I've got a table and I'm trying to use the save() method to update/create lines. The problem is that it always create new lines. The following code gives me about 12 lines each time I run it. They don't have a unique id before inserting them but the combination of name and DateTimeCode is unique. Is there's a way to use those two in order for laravel to recognize them as exist()? Should I consider using if exist with create and update instead?

foreach ($x as $y) {
    $model = new Model;
    $model->name = ''.$name[$x];
    $model->DateTimeCode = ''.$DateTimeCode[$x];
    $model->value = ''.$value[$x];
    $model->someothervalue = ''.$someothervalue[$x];
    $model->save();
};

Upvotes: 1

Views: 8710

Answers (2)

Hill
Hill

Reputation: 429

I assume this would work in laravel 4.x:

 foreach ($x as $y) {
    $model = Model::firstOrCreate(array('name' => name[$x], 'DateTimeCode' => DateTimeCode[$x]));
    $model->value = ''.$value[$x];
    $model->someothervalue = ''.$someothervalue[$x];
    $model->save();
};

Upvotes: 5

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

I think that in this case you will need to search for it before updating or creating:

foreach ($x as $y) {
    $model = Model::where('name', name[$x])->where('DateTimeCode', DateTimeCode[$x])->first();

    if( ! $model)
    {
        $model = new Model;
        $model->name = ''.name[$x];
        $model->DateTimeCode = ''.DateTimeCode[$x];
    }

    $model->value = ''.$value[$x];
    $model->someothervalue = ''.$someothervalue[$x];
    $model->save();
};

Upvotes: 4

Related Questions