簡體   English   中英

在null(Laravel 5.3)上調用成員函數copy()

[英]Call to a member function replicate() on null (Laravel 5.3)

我正在使用laravel 5.3,我必須從表中存儲一個重復的行,這是我的功能,並且我收到以下錯誤消息。 對null的成員函數plicate()的調用請幫助我修復它的功能

public function copy($id){

$task = Task::find(1);
$newTask = $task->replicate();
$newTask->save();
    }

```

公共功能副本($ id){

$task = Task::find(1);
if (null !== $task) {
    $newTask = $task->replicate();
    if (null !== $newTask) {
        $newTask->save();
    }
}

}```

為了使這個問題更易讀,您可以使用Laravel的Eloquent的firstOrFail方法 如果沒有找到ID為1的結果, Illuminate\\Database\\Eloquent\\ModelNotFoundException拋出Illuminate\\Database\\Eloquent\\ModelNotFoundException ,您可以捕獲並繼續進行。

代碼如下:

public function copy($id) {
   try {
     $task = Task::firstOrFail(1);
     $newTask = $task->replicate();
     $newTask->save();
   } catch(Exception $e) {
      // If nothing found with that (1) id, then the throws exception is catched here!
   }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM