Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel updateOrCreate with auto-incremental database

My purpose is to update if the value exists, else inserts a new row in the database table after submitting the form.

The problem is, the function here adds new columns in db table instead of updating them.

Here's my function :

MyModel::updateOrCreate(array(
    'myField' => 'myValue',
))
    ->where('myAutoIncrementalField', '=', '5')
    ->where('myPrimaryKey', '=', '8');

My database table is like that :
1. myPrimaryKey (not auto incremental and is fillable on model.)
2. myAutoIncrementalField (auto incremental and cannot be fillable on model.)

Thank you in advance.

like image 798
saimcan Avatar asked Dec 15 '14 07:12

saimcan


2 Answers

This is how you use this method:

Model::updateOrCreate(
   ['primary_key' => 8],
   ['field' => 'value', 'another_field' => 'another value']
);

As 1st param pass an array of fields that are unique, or in your case, the primary key. Non-unique fields don't make sense here obviously just like passing anything along with the PK.

2nd param is an array of values that should be updated/created too, but being ignored in the unique/pk search.

like image 116
Jarek Tkaczyk Avatar answered Sep 24 '22 05:09

Jarek Tkaczyk


You cannot use where functions with this method. You have to include the where clauses in the array.

MyModel::updateOrCreate(array(
    'myField' => 'myValue',
    'myAutoIncrementalField' => '5',
    'myPrimaryKey' => '8'
));
like image 42
Jerodev Avatar answered Sep 22 '22 05:09

Jerodev