Method orderBy does not exist in Laravel Eloquent?

烂漫一生 提交于 2020-04-29 07:24:08

问题


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.


回答1:


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.




回答2:


just use the one line code it will work fine

$product= Product::orderBy('created_at','desc')->get();



回答3:


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

$post = Post::orderBy('id', 'DESC')->get();



回答4:


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.




回答5:


Your query is wrong.

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




回答6:


$table_Data = DB::table('tbl_product')->orderBy('id','DESC');

You can use this...




回答7:


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



来源:https://stackoverflow.com/questions/37760963/method-orderby-does-not-exist-in-laravel-eloquent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!