2016-11-19 43 views
0

我使用Laravel 5.3。Laravel使用Get params in Eloquent/DB

我有一個存儲庫,對於特定的查詢,我想用$ _GET參數進行過濾。

有沒有辦法做到這一點,如:

protected function queryGetAds(Request $request) 
{ 
    return $this->model 
     ->select('*') 
     ->where('status', '=', 1) 
     ->where(function ($q) use ($request) { 
      if ($request->from) { 
       $q->where('ad_price', '>=', $request->from); 
      } 
     }) 
     ->with('user'); 
} 

從現在開始,我有一個錯誤:

Type error: Argument 1 passed to App\Repositories\AdRepository::queryGetAds() must be an instance of Illuminate\Http\Request, none given,

有沒有辦法做到這一點?也許更好的方法..?

我想在$ _GET中添加一個「從」或「到」參數的位置。

+0

這聽起來像你已經導入(使用'使用')錯誤的類和laravel不認爲它適合。 –

+0

我認爲它與'$ request-> from'語法有關。你嘗試過使用'$ request-> input('field_name')'語法嗎? – Abrar

回答

0

,可以有以下方法:

protected function queryGetAds(Request $request) 
{ 
    // ... 
} 

好像是,你在呼喚自己這種方法,而不是傳遞所需的參數所以錯誤出現。您可以調用它時傳遞Illuminate\Http\Request對象作爲該方法的參數或剛剛擺脫從你的方法該參數和使用方法中的request全局函數來獲得請求的實例,例如:

protected function queryGetAds() 
{ 
    $request = request(); // or app('request') or other alternatives 
    // Rest of your code should work from here... 

    return $this->model ... // Rest of the code ... 
} 

另外,還可以通過所有的請求參數在你的方法,如:

protected function queryGetAds(Array $requestParams) 
{ 
    return $this->model 
    ->select('*') 
    ->where('status', '=', 1) 
    ->where(function ($q) use ($requestParams) { 
     if(isset($requestParams['from'])) { 
      $q->where('ad_price', '>=', $requestParams['from']); 
     } 
    }) 
    ->with('user'); 
} 

而且通過PARAMS調用方法時,例如:

$someObject->queryGetAds(request()->all());