0
votes

I use Laravel 5.3.

I have a Repository, and for a specific query, I want to use $_GET params for filtering.

Is there a way to do this like :

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

From now, I have an error :

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

Is there a way to do this ? maybe a better way .. ?

I want to add a where when I got a "from" or "to" param in $_GET.

1
That sounds like you have imported (using use) the wrong class and laravel doesnt find it suitable. - Ivanka Todorova
I think it has something to do with the $request->from syntax . Have you tried using $request->input('field_name') syntax instead ? - Abrar

1 Answers

0
votes

You have following method:

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

Seems like that, you are calling this method by yourself and not passing the required parameter so the error arose. You can either pass the Illuminate\Http\Request object as parameter of this method when calling it or just get rid of this parameter from your method and use the request global function inside the method to get the request instance, for example:

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 ...
}

Also, you can pass all the request params in your method like:

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

And pass the params when calling the method, for example:

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