2

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 ?

1
  • What's currently not working? Commented Sep 27, 2019 at 7:05

4 Answers 4

4

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

Comments

2

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();

}

5 Comments

I receive this error : Method App\Cpref::__toString() must return a string value
The field in the database is smallint
Edited answer please try now.
is it possible to create the object new Cpref(); only once outside the loop?
Yes, @Yasin Patel given the answer below the answer. Cpref::insert($data); with array you can do it.
2
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();
 } 
}

Comments

1
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();

 } 
}

Comments

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.