2017-09-25 29 views
0

我們有一個DB 100級的用戶。例如如何看待「不爲模型查詢結果」在Laravel

這裏是路線

Route::get('/users/{user}/edit', '[email protected]'); 

這裏是方法

public function edit(User $user) 
    { 
     $hi = 'Hello'; 
     return $hi; 
    } 

好吧..如果我做這樣的事情

http://localhost/users/99/edit | WORKS 
http://localhost/users/100/edit | WORKS 
http://localhost/users/101/edit | PROBLEM 

如何解決用戶何時更改來自不存在記錄的URL的值?

+0

這是因爲ID爲101的用戶不存在,您可以傳遞ID並在try塊中使用'find'方法並在異常重定向時 –

+0

重定向到404頁面 – C2486

+0

這就是laravel的正確行爲,需要創建Handler來呈現404頁面。 –

回答

0

在這種情況下,我會通過用戶ID作爲參數,而不是明確的結合:

Route::get('/users/{userId}/edit', '[email protected]');

當一種模式是無法發現你會得到一個ModelNotFoundException拋出異常,你可以捕捉它和治療這種情況下

控制器:

use Illuminate/Database/Eloquent/ModelNotFoundException; 

[...] 

public function edit($userId) 
    { 
     try{ 
      $user = User::find($userId); 
      //do some stuff 
     } catch (ModelNotFoundException $e){ 
      //treat error (log the activity, redirect to a certain page) 
      //or display a 404 page 
      //dealer's choice 
     } 
    } 
+0

Laravel隱含地做着同樣的事情。 ..你最終拋出已被拋出的異常,並且OP想要實際處理它。 –

+0

@DeepanshSachdeva Laravel確實返回了一個404(http)的http狀態碼,我也指出OP可以做其他各種事情,你不同意嗎? –

+0

我同意......你的回答是一個可行的解決方案,但有一個處理器來呈現404頁面會使它更通用。 –

0

在您的情況下,用戶不能找到,這是一個4 04:

public function edit(User $user) 
{ 
    $user = false; // dummy/example 
    if ($user) { 
     return $your_results; 
    } else { 
     return view('errors.404'); 
     // assuming you have a folder called 'errors' inside your 'views' folder 
     // and the file name is `404.blade.php` 
     // and are using blade files. 
    }   
} 

如果用戶可以找到,顯示任何你需要的,否則,顯示404刀片視圖。