34

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.

Harrison
  • 2,560
  • 7
  • 29
  • 55

7 Answers7

54

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.

Alexey Mezenin
  • 158,981
  • 26
  • 290
  • 279
24

just use the one line code it will work fine

$product= Product::orderBy('created_at','desc')->get();
gaurav
  • 309
  • 2
  • 7
4

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

Bilawal Awan
  • 422
  • 3
  • 13
2

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

$post = Post::orderBy('id', 'DESC')->get();
baduker
  • 19,152
  • 9
  • 33
  • 56
Pushpendra Pal
  • 115
  • 1
  • 14
0

You are first getting all() data and then trying to sort which is wrong. You have to fix this by removing

$products = Product::all()

and changing your code into something like this

if ($search_value) {
    $products = Product::where('name', 'LIKE', "%$search_value%");
}
else {
    $products = Product::orderBy('created_at', 'desc')->skip(10)->take(10)->with('tags')->get();
}

Hope you get idea to tweak your code.

KuKeC
  • 4,392
  • 5
  • 31
  • 60
0

Your query is wrong.

remove all from $products = Product::all() and then put get() at the end of your query.

Himanshu Raval
  • 790
  • 7
  • 19
0
$table_Data = DB::table('tbl_product')->orderBy('id','DESC');

You can use this...

Viral M
  • 261
  • 2
  • 14