1

I want to move all the data from the post table into the CityPost table, I use foreach but why only one data entry,

 $store = new CityPost;
           $post = Post::all();
           foreach($post as $p){
               $store->user_id = 14; 
               $store->title = $v->title;
               $store->desc = $v->desc;
               $store->save();
           }
           dd($store);

I want all user_id in the PostCity table to be 14

1
  • 1
    because you only created one new model instance after the first save it now has an id and every call to save after that is just an update on the same record Commented Nov 27, 2019 at 3:57

2 Answers 2

5

You should create CityPost model in foreach:

       $post = Post::all();
       foreach($post as $p){
           $store = new CityPost;
           $store->user_id = 14; 
           $store->title = $v->title;
           $store->desc = $v->desc;
           $store->save();        
       }
       dd($store);
Sign up to request clarification or add additional context in comments.

Comments

2

You can do is try different way like below

$post = Post::all();
$stores = [];
foreach($post as $p){
    $store = new CityPost;
    $store->user_id = 14; 
    $store->title = $v->title;
    $store->desc = $v->desc;
    $stores[] = $store->save();

   //if $store->save() is boolean then you can use create method use save() or create() only one

   $new = CityPost::create(['user_id'=>14,'title'=>$p->title,'desc'=>$p->desc]);
   $stores[] = $new;
}
dd($stores);

or you can try another way like bulk update without calling DB multiple time

    $post = Post::all();
    $data = [];
    foreach($post as $p){
        $store->user_id = 14; 
        $store->title = $v->title;
        $store->desc = $v->desc;
        $data[] = ['user_id'=>$store->user_id,'title'=>$p->title,'desc'=>$p->desc];
    }
    CityPost::insert($data);

3 Comments

save returns a bool and in your first example you are updating $store not creating new instances, which is the same problem the OP has in their code currently
btw there isn't a question of whether save returns bool or not, it does return bool ... thanks for clarifying your answer :)
i have put both so developer can select prefer one . i hope he won't use both :)

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.