Search code examples
phplaravellaravel-9

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


I can't see what's wrong with this code. Please help me.

public function index()
{
    return view('listings.index', [
        'listings' => Listing::latest()->filter((['tags']))->get()
    ]);

Solution

  • Like Mr.Karl Hill, mentioned you forget to close your index method body, but this is not your problem, anyway, you're trying to get access to a method called filter which you didn't define on your Listing model, and the filter method doesn't provide by the laravel query builder or Eloquent ORM itself, but it's possible to create a scope in your model so then you can use your scope to filter your data but also, you don't need to do it because laravel already provided one for you that'll help you to filter out your data coming from your model easily which is whereIn() it accepts an array it'll loop your records one by one on the list that you provided for and filter your data depends on that array that you gives to it, and also if you've separated table for tags you can define a One-to-Many relationship on your model then you can use anonymous where statement provided by laravel Eloquent ORM like below's peace of codes to filter your data using that relationship that you created on your Listing table:

    $filteredData = Listing::latest()->whereHas('tags', function ($query) use ($tags) {
        $query->whereIn('name', $tags);
    })->get();