i have create a duplicate row using replicate here is my function
public function copy($id){
$task = Task::find($id);
$copy = $task->replicate();
$copy->save();
session()->flash('msg','successfully Copied!');
}
i want that on copy my name field should changed as
Task 1 - copy
if i make 2nd copy it should be as
Task 1 - copy 2
Please help me to make it accordingly
You can try something like this
$task = Task::find($id);
$copy = $task->replicate();
$copy->name = $copy->name.'2';
$copy->save();
Something like this should work
$task = Task::find($id);
$copy = $task->replicate();
// If the name contains the word 'copy' create the next one
if (str_is('copy', $copy->name)){
//Get the last word
$words = explode(' ', $copy->name);
$last_word = array_pop($words);
// If the last word is 'copy' create the right number, else it's the first copy
if ($last_word == 'copy'){
$copy->name = str_finish($copy->name, ' 2');
} else {
$number = strval(intval($last_word) + 1);
$copy->name = str_finish(implode(" ", $words), ' ' . $number);
}
// Else create the first one
} else {
$copy->name = str_finish($copy->name, ' - copy');
}
$copy->save();