2014-05-03 82 views
1

幾天前我開始學習Laravel。 現在我的控制器中有一個變量出現問題,我總是得到這個錯誤:「Undefined variable:server_id」。Laravel控制器變量

我的路由文件看起來是這樣的:

Route::get('servers/{server_id}','[email protected]'); 

而且在相關的控制器操作方法:

public function show($server_id) 
{ 
    $details = Server::with(array('details' => function($query) 
    { 
     $query->where('server_id', '=', $server_id); 

    }))->get(); 

    return View::make('servers.show')->with('details', $details); 
} 

我可以使用var。 $ server_id並將其傳遞給視圖。但是我無法在數據庫查詢的where子句中使用它。

我希望有人能解釋我是什麼問題以及如何解決這個問題。

回答

0

您正在使用閉包並且它有不同的範圍,您應該使用使用關鍵字將$ server_id變量傳遞給它。

PHP文件說:

Closures may also inherit variables from the parent scope. Any such variables must be passed to the use language construct. Inheriting variables from the parent scope is not the same as using global variables. Global variables exist in the global scope, which is the same no matter what function is executing. The parent scope of a closure is the function in which the closure was declared (not necessarily the function it was called from).

Read more about Anonymous functions

public function show($server_id) 
{ 
    $details = Server::with(array('details' => function($query) use ($server_id) 
     { 
      $query->where('server_id', '=', $server_id); 
     }))->get(); 

    return View::make('servers.show')->with('details', $details); 
} 
1

Model::with()方法意味着,當你實例化一個模型的對象,你也同時加載一些其他集合。這對於避免不必要的數據庫調用很有用。

我不能確定你的代碼,但它看起來像你想找到服務器的ID爲$ server_id,而不是加載一些其他的東西。如果這是正確的,你可以清理你的代碼很多,像這樣:

public function show($server_id) 
{ 
    $details = Server::find($server_id); 
    return View::make('servers.show')->with('details', $details); 
}