Furquan
Furquan

Reputation: 1842

Filter in Laravel showing BadMethodCallException

I have a collection from below query

$order = $company->Orders()
            ->whereBetween('created_at', [$this->start_date, $this->end_date])
            ->whereNull('is_cancel')
            ->whereNull('is_removed')
            ->whereNull('deleted_at');

Now I want to filter out all the orders who are expired

$orders = $orders->filter(function($value,$key){
                return  $this->expiry($value) < Carbon::now();
            });

above code is throwing error

BadMethodCallException with message 'Call to undefined method Illuminate/Database/Query/Builder::filter()'

I can use $orders->get()->filter() but I need to check furthur in the collection for counts and mapping etc, so I dont want to use get here. Any help is much appreciated.

Upvotes: 1

Views: 217

Answers (1)

Mihai Matei
Mihai Matei

Reputation: 24276

filter is undefined because it is a method defined on the collection, not on the query builder. What you need to do is to get the results before filtering them:

$orders = $company
    ->Orders()
    ->whereBetween('created_at', [$this->start_date, $this->end_date])
    ->whereNull('is_cancel')
    ->whereNull('is_removed')
    ->whereNull('deleted_at')
    ->get()
    ->filter(function($value) {
        return $this->expiry($value) < Carbon::now();
    });

Upvotes: 3

Related Questions