I have a piece of code like this:
$products = Product::all()
if ($search_value) {
$products = $products->where('name', 'LIKE', "%$search_value%");
}
$products = $products->orderBy('created_at', 'desc')->skip(10)->take(10)->with('tags')->get();
I got the following error:
BadMethodCallException in Macroable.php line 81:
Method orderBy does not exist.
I guess orderBy
need to follow Product::
directly, but I can't save $products = Product::
, can I?
Any suggestions? Thanks.
You're trying to use orderBy()
method on Eloquent collection. Try to use sortByDesc()
instead.
Alternatively, you could change $products = Product::all();
to $products = new Product();
. Then all your code will work as you expect.