0

I'd like to add a method to my Laravel Product model which filters by name attr and returns a collection of all matching products, here's what I've got:

Product.php

public function filterByName($query)
{
    return $this->where('name','LIKE','%'.$query.'%')->get();
}

ProductController.php

$products = collect(new Product);
$products->filterByName($name);

What's the correct usage of this? Do I need to use a QueryFilter?

Community
  • 1
  • 1
f7n
  • 1,476
  • 3
  • 22
  • 42

1 Answers1

5

Are you talking about scope?

public function scopeByName($query, $param)
{
    return $query->where('name','LIKE','%'.$param.'%');
}

and then

$products = Product::byName('xyz')->get();
Prafulla Kumar Sahu
  • 9,321
  • 11
  • 68
  • 105