Laravel Copy record and duplicate with new values

How can i copy a record and save it with a different value for 1 or more field?

for example: get----> first_name, last_name, civil_status, work

i want to copy the first name, and last name then insert it with a new civil status and work.

1

4 Answers

You could use the replicate method of model like this:

// Retrieve the first task $task = Task::first(); $newTask = $task->replicate(); $newTask->project_id = 16; // the new project_id $newTask->save(); 
3

You could use replicate method. This will create a new object with the same values except the primary key, and the timestamps. After that you can save your model:

$task = Task::find(1); $new = $task->replicate(); 

If you want you could change a property

$new->project = $otherProject; 

and then

$new->save(); 

if you want the new ID, easy:

$newID = $new->id; 
4

You can use replicate() and then update that row:

Model::find(1)->replicate()->save(); $model = Model::find(1); $model->project_id = $new_project_id; $model->save(); 
1

also you can do like this.

$selected = Model::find(1); $copy = $selected->replicate()->fill( [ 'project_id' => $new_project_id, ] ); $copy->save(); 

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

You Might Also Like