【问题标题】:Laravel use Get params in Eloquent / DBLaravel 在 Eloquent / DB 中使用 Get params
【发布时间】:2016-11-20 05:51:50
【问题描述】:

我使用 Laravel 5.3。

我有一个存储库,对于特定查询,我想使用 $_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');
}

从现在开始,我有一个错误:

类型错误:参数 1 传递给 App\Repositories\AdRepository::queryGetAds() 必须是 Illuminate\Http\Request,没有给出,

有没有办法做到这一点?也许更好的方法..?

当我在 $_GET 中获得“from”或“to”参数时,我想添加一个 where。

【问题讨论】:

  • 听起来你已经导入(使用use)错误的类和laravel 不觉得它合适。
  • 我认为这与$request->from 语法有关。您是否尝试过改用$request->input('field_name') 语法?

标签: php laravel


【解决方案1】:

你有以下方法:

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');
}

并在调用方法时传递参数,例如:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-11-26
    • 2014-10-07
    • 2015-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多