2016-10-28 60 views
0

我已創建使用複製在這裏重複行是我的功能我想補充的名字領域的一些附加數據(Laravel 5.3)

public function copy($id){ 

    $task = Task::find($id); 
    $copy = $task->replicate(); 
    $copy->save(); 
    session()->flash('msg','successfully Copied!'); 
} 

我想,在複製我的名字字段應該改變

任務1 - 複製

如果我做第二個副本,它應該是爲

任務1 - 副本2

請幫我使其相應

回答

0

你可以嘗試這樣的

$task = Task::find($id); 

$copy = $task->replicate(); 
$copy->name = $copy->name.'2'; 
$copy->save(); 
+0

其更換名稱與副本2我還需要名稱 現在意味着如何連接名稱與副本詞@jaimin –

+0

@recove我已經改變了我的答案。你想要這樣的東西嗎? – Jaimin

+0

非常接近 我現在使用這個 $ copy-> name = $ copy-> name。「」.'Copy /'.$ id; 如果我爲copyid創建副本它創建新副本爲副本Copy/29,因爲它的ID是29,如果我再次複製副本它應該是複製/ 30但現在它的製作複製/ 29 @jaimin –

0

像這樣的東西應該工作

$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();