Abdallah Sakre
Abdallah Sakre

Reputation: 915

How to loop through an array and store its values in Laravel

I have the following array :

$catprefs = $request['catpref'];

Vardump :

array(5) { [0]=> string(1) "1" [1]=> string(2) "11" [2]=> string(1) "2" [3]=> string(1) "3" [4]=> string(1) "4" }

I need to loop this array and store each one of the values in a new row as follows :

foreach ($catprefs as $save_catp) {
      $save_catp = new Cpref();
      $save_catp->user_id = $user_id;
      $save_catp->qatype = ????? ; // need to put the array value here
      $save_catp->type = 1;

      $save_catp->save();
}    

How can I store each value of the array in the above insert ?

Upvotes: 2

Views: 3224

Answers (4)

Yasin Patel
Yasin Patel

Reputation: 5731

You can also use bulk insert as below :

$data = [];
foreach($catprefs as $key => $val){
  $data[] =[
    'user_id' => $user_id,
    'qatype' => $val,
    'type' => 1
   ]
}

Cpref::insert($data);

Upvotes: 4

Pragnesh Chauhan
Pragnesh Chauhan

Reputation: 8476

foreach($catprefs as $save_catp){
$save_catp = new Cpref();

you are using $save_catp in for loop and Cpref object, you need to change one of the variables.

if(!empty($catprefs)){
  foreach($catprefs as $key => $val){

  $save_catp = new Cpref();
  $save_catp->user_id = $user_id;
  $save_catp->qatype = $val; // array value goes here
  $save_catp->type = 1;


  $save_catp->save();

 } 
}

Upvotes: 1

Jithesh Jose
Jithesh Jose

Reputation: 1814

if(!empty($catprefs))
{
 foreach($catprefs as $key => $row)
 {
   $save_catp = new Cpref();
   $save_catp->user_id = $user_id;
   $save_catp->qatype = $row ; // need to put the array value here
   $save_catp->type = 1;
   $save_catp->save();
 } 
}

Upvotes: 2

Dilip Hirapara
Dilip Hirapara

Reputation: 15316

Try this.

foreach($catprefs as $save_catp){

      $cpref= new Cpref();
      $cpref->user_id = $user_id;
      $cpref->qatype = $save_catp; // need to put the array value here
      $cpref->type = 1;
      $cpref->save();

}

If you use $key => $value

foreach($catprefs as $key => $value){

      $cpref= new Cpref();
      $cpref->user_id = $user_id;
      $cpref->qatype = $value; // need to put the array value here
      $cpref->type = 1;
      $cpref->save();

}

Upvotes: 2

Related Questions