'Laravel copy record and duplicate with new values But not with unique field

I want to duplicate my records with a new value.

I am using these codes and they are working well with unique field (id).

$task = tableName::find($request->id);
    $newTask = $task->replicate();
    $newTask->newField= 2;
    $newTask->save();

My table looks like :

id no first second newField
1 45 1000 650 1
2 52 4500 45 1
3 45 1250 75 1
4 58 7500 86 1
5 45 250 72 1

i want to duplicate all my rows with a new value. Just newField must be 2.



Solution 1:[1]

You need to fetch all records against a specific no. Try something like this

$tasks = tableName::where('no',$request->id)->where('newField',1)->get();
foreach($tasks as $task)
{
    $newTask = $task->replicate();
    $newTask->newField= 2;
    $newTask->save();
}

Please check official documentation as well.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aqib Javed