Home > Back-end >  Call to undefined method Illuminate\Database\Eloquent\Builder::filter()
Call to undefined method Illuminate\Database\Eloquent\Builder::filter()

Time:08-01

I try to make Filters.

When I have:

    public function index(OrderFilter $filter): View
    {
        $items = Order::withTrashed()->filter($filter)->paginate(10);

        return view($this->viewsPath . self::INDEX_ACTION, [
            'items' => $items,
            'perPage' => 10,
        ]);
    }

I take mistake Call to undefined method Illuminate\Database\Eloquent\Builder::filter()

But when I delete filter($filter) I have not any mistake but my filtration does not work.

How can I make filtration correctly?

OrderFilter

<?php

namespace App\Filters\Orders;

use App\Filters\QueryFilter;

class OrderFilter extends QueryFilter
{
    public function id(string $id)
    {
        $this->builder->where('id', $id);
    }

    public function name(string $name)
    {
        $this->builder->where('name', 'like', '%' . $name . '%');
    }

    public function address(string $address)
    {
        $this->builder->where('address', 'like', '%' . $address . '%');
    }
}

CodePudding user response:

filter() is a method that is available on collections. So when you do

$query = Order::withTrashed()->filter($filter)->paginate(10);

what you are doing is appending the filter method to the query builder instance and this will give you error.

In order to fix this, you can do:

$query = Order::withTrashed()->paginate(10)->filter($filter);

and, this won't give you error because now you're applying filters on the collection.

CodePudding user response:

If you want to conditionally apply filters by modifying the query builder, maybe consider the EloquentFilter package by Tucker-Eric.

  • Related