PrStandup
PrStandup

Reputation: 343

Add a filter function on laravel query builder

I am getting some data from a model like:

public function getExternalCodes()
{
    return ExternalService::get()->pluck('add_id')->toArray();
}

Now before this I want to apply a function to filter the data by date:

public function getExternalCodes()
{
    $query =  ExternalService::get()->pluck('add_id')->toArray();

    return $query->filterByDate($query, new ExternalServce);
}

My filter by date function

private function filterByDate(Builder $query, Model $model)
    {

        if (!request()->has('interval')) {

            return $query;
        }

        $period = json_decode(request()->get('interval'));

        if ($period->from) {

            $query->where("{$model->getTable()}.created_at", ">=", Carbon::parse($period->from)->startOfDay());
        }

        if ($period->to) {

            $query->where("{$model->getTable()}.created_at", "<=", Carbon::parse($period->to)->endOfDay());
        }

        return $query;
    }

However I can not do it right now since I am calling get() before applying the filter. Any idea how to go about it ?

And yes dont add a question to filter with where since I can not do that

Upvotes: 3

Views: 7681

Answers (1)

Alexey Mezenin
Alexey Mezenin

Reputation: 163798

Since you're using Eloquent models, use a local scope for that:

private function scopeFilterByDate($query)
{
    ....
}

Then use the scope with:

public function getExternalCodes()
{
    return ExternalService::filterByDate()->pluck('add_id')->toArray();
}

Upvotes: 3

Related Questions