Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method orderBy does not exist in Laravel Eloquent?

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.

like image 261
Harrison Avatar asked Jun 11 '16 07:06

Harrison


4 Answers

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.

like image 50
Alexey Mezenin Avatar answered Nov 03 '22 12:11

Alexey Mezenin


just use the one line code it will work fine

$product= Product::orderBy('created_at','desc')->get();
like image 23
gaurav Avatar answered Nov 03 '22 13:11

gaurav


If you want to get the list of all data and grab it in descending order try this:

$post = Post::orderBy('id', 'DESC')->get();
like image 2
Pushpendra Pal Avatar answered Nov 03 '22 12:11

Pushpendra Pal


use sortByDesc('id') or simple sortBy() inside use the variable through which you wanna sort like i add id

like image 2
Bilawal Awan Avatar answered Nov 03 '22 13:11

Bilawal Awan