8

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

4
  • Eloquent can't insert/update multiple rows, you need to process them one by one. The insert method is in fact Query\Builders and it doesn't use Eloquent features at all (eg. timestamps and so on). Commented Nov 24, 2014 at 15:56
  • is there any other way in Eloquent or Query\Builder that I could create entry or update if data presence @JarekTkaczyk . Because I need to updateOrCreate nearly 20-50 data is it a good practice to do it one by one?? Commented Nov 25, 2014 at 3:46
  • Good practice in what way? You can either write 3 lines of code and let Eloquent do the job, or say 13 lines of code, where you do the job. Eloquent has firstOrNew method, which is the way to go. Commented Nov 25, 2014 at 7:50
  • 1
    Jarek Tkaczyk already gave you the answer and there's no way around it. What are you looking for? (since you added a bounty) Commented Nov 27, 2014 at 22:35

2 Answers 2

10
+50

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]
);
Sign up to request clarification or add additional context in comments.

2 Comments

How would you use updateOrCreate for updating or creating multiple rows of data, but each row you are updating is updating different columns in the DB?
put the updateOrCreate inside of the loop
1

I think you are working with the customized framework of laravel so you have UpdateOrCreate method because laravel not provides such methods if my assumption is true than below written code may b useful for your application

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']);
  $attr_array = array('fk_workouts_id','fk_users_id','fk_exercises_id','section','status','item_index','updated_at');

  foreach($exerciseData as $exerciseid){

      $val_array = array($userId,$exerciseid,$exerciseValue['section_type'],1,$item_index,$workoutDetails['updated_at']);
      WorkoutExercise::updateOrCreate($attr_array,$val_array);
  }
}

But if you are not using such kind of customized framework than please try with the below code it may work fine

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){

    $item_index = $index+$kkey+1;

    // Retrieve the record by the fk_workouts_id, or create it if it doesn't exist...
    $exercise = WorkoutExercise::firstOrCreate($attributes = array('fk_workouts_id' => $id));

    /* assign the values of other fields to store in database table*/
    $exercise->fk_users_id      = $userId;
    $exercise->fk_exercises_id  = $exerciseid;
    $exercise->section          = $exerciseValue['section_type'];
    $exercise->status           = 1;
    $exercise->item_index       = $item_index;
    $exercise->updated_at       = $workoutDetails['updated_at'];
    $exercise->save(); // update the record
  }
}

good luck...:)

2 Comments

the queries will be executed throughout the foreach right?? is there a way to minimize the queries??
I don't think so we will have the solution for this requirements. But if I found that then will surely revert back to you....

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.