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.
just use the one line code it will work fine
$product= Product::orderBy('created_at','desc')->get();
If you want to get the list of all data and grab it in descending order try this:
$post = Post::orderBy('id', 'DESC')->get();
use sortByDesc('id') or simple sortBy() inside use the variable through which you wanna sort like i add id
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With