3

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

1 Answer 1

3

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();
}
Sign up to request clarification or add additional context in comments.

6 Comments

the issue with that is that this filter is on repositories and its being used with 10 different other models. So I cant do that
@PrStandup put it into a trait or create a base model class.
hmm do you think is okay to place it on base eloquent model ?
@PrStandup I mean create some kind of base model class which extends Model. I would use trait.
@PrStandup yes it does.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.