Using updateOrCreate for multiple data insert in Laravel
eloquent, laravel, laravel-4, orm, php
Solution
You can try like,
First Way
$user = User::firstOrNew(array('name' => 'satish'));
$user->field = 'value';
$user->save();
It will check for user `name=satish` if found then return it. If not found then create new and return. Then you can set field values.
Check this link. http://laravel.com/docs/4.2/eloquent#insert-update-delete
Second Way Mannually Check record is exists.
$arr=array('field'=>"value");
$row = User::find($id);
if ($row === null) {
//Insert your record
} else {
//update your record
}
UPDATED
You can also use `updateOrCreate` - update an existing model or create a new model if none exists. `updateOrCreate` persists the model, so there's no need to call `save()`.
Example-
// If there's a flight from Oakland to San Diego, set the price to $99.
// If no matching model exists, create one.
$flight = App\Flight::updateOrCreate(
['departure' => 'Oakland', 'destination' => 'San Diego'],
['price' => 99]
);
Problem
I have used the following insert array to insert multiple entries in Laravel `Eloquent ORM` ``` $i = 0; foreach($exerciseValArray as $kkey=>$exerciseValue){ if($exerciseValue['exercise'] =='' || $exerciseValue['section_type'] == ''){ return Response::JSON(array('errors'=>array('Error in workout exercise section'))); } $exerciseData = explode(',',$exerciseValue['exercise']); foreach($exerciseData as $exerciseid){ $insertArray[$i]['fk_workouts_id'] = $id; $insertArray[$i]['fk_users_id'] = $userId; $insertArray[$i]['fk_exercises_id']= $exerciseid; $insertArray[$i]['section'] = $exerciseValue['section_type']; $insertArray[$i]['status'] = 1; $insertArray[$i]['item_index'] = $index+$kkey+1; $insertArray[$i]['updated_at'] = $workoutDetails['updated_at']; $i++; } } WorkoutExercise::insert($insertArray); ``` The above code works fine and inserts the data array in to the database. I have learnt the usage of `Model::updateOrCreate` and used it in some of my modules successfully (i.e) ``` Model::updateOrCreate($attributes = array('key' => 'value'), $values = array('key' => 'value')); ``` My question is how to edit the above insert snippet so that I could use `Model::updateOrCreate` in it. My `$attributes` fields are 'fk_workouts_id','fk_users_id','fk_exercises_id' and the rest in the `$values` to be changed. I have no idea how to implement this. Pls help...