Fed
Fed

Reputation: 85

Laravel Copy record and duplicate with User IDs

How can i copy a record and save it with a different value for 1 or more field? for example I have a table(post table) with following columns - ID | User ID | Post Title | Post Type And User Table(user) with following columns - ID | Username | Email | Password

What i need to do is - When the saving post data needs to be duplicate with user ids

For example - In user table there is 10 users and when i save the post it should be duplicate for all ten user id

   ID | User ID | Post Title | Post Type
   1  | 1       | Test Post  | Public   
   2  | 2       | Test Post  | Public 
   3  | 3       | Test Post  | Public 
   4  | 4       | Test Post  | Public 
   5  | 5       | Test Post  | Public 
   6  | 6       | Test Post  | Public 
   7  | 7       | Test Post  | Public 
   8  | 8       | Test Post  | Public 

enter image description here

Upvotes: 1

Views: 863

Answers (1)

Vikash Pathak
Vikash Pathak

Reputation: 3562

As suggested, you can do this using model replication. Like

$post = Post::find(12892);         //change with your id.


// get all the users.

$users = User::all();

foreach($users as $user){
    $newPost = $post->replicate();
    $newPost->user_id = $user->id;

    // save post.
    $newPost->save();
}

Upvotes: 1

Related Questions