Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Ajvanho's avatar
Level 14

replicate() with DB facade

How to replicate table row with DB facade? With elequent:

$post = Post::find(1);
$newPost = $post->replicate()->fill(
    [
        'project_id' => $new_project_id,
    ]
);
$newPost->save();
0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

Not sure you you dont just use eloquent. But try this (you might want to add timestamps manually if you want those)

$data = DB::table('posts')->where('id', 1)->select(['project_id', 'other_column'])->first();
$data['project_id'] = $new_project_id;
DB::table('posts')->insert($data);
1 like
SilenceBringer's avatar

@ajvanho I do not think it exists. But you can do it manually

$rowData = Arr::exclude(DB::table('your_table')->where('id', 1)->first()->toArray(), 'id');
rowData['project_id'] = $new_project_id;
DB::table('your_table')->insert($rowData);
1 like

Please or to participate in this conversation.