Reputation: 2690
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.
Upvotes: 36
Views: 92390
Reputation: 1
Modelname::query()->where('field_name','attribute')->orderBy('updated_at', 'desc')->get();
Upvotes: 0
Reputation: 710
If you are working on laravel collections and fetching records with Query so we have various ways to fetch the data.
Product::orderBy('created_at')->get() or DB::table('products')->orderBy('created_at')->get();
.hadMany
to orders
and we want to get ordered records from it then we can do in one way:$product = Product::first(); $product->orders;
// Now you can not
use operations on this so you can do something
like:
$product->orders()->orderBy('created_at')->first(); //This will give the latest record.
Let me know if need clarifications regarding this.
there are also a lot of ways but need to have clear idea about Laravel collections. One is Illuminate\Support\Collection
and another is Illuminate\Database\Eloquent\Collection
. They have some common methods but not all.
Upvotes: 0
Reputation: 432
use sortByDesc('id') or simple sortBy() inside use the variable through which you wanna sort like i add id
Upvotes: 4
Reputation: 125
If you want to get the list of all data and grab it in descending order try this:
$post = Post::orderBy('id', 'DESC')->get();
Upvotes: 2
Reputation: 261
$table_Data = DB::table('tbl_product')->orderBy('id','DESC');
You can use this...
Upvotes: 0
Reputation: 409
just use the one line code it will work fine
$product= Product::orderBy('created_at','desc')->get();
Upvotes: 24
Reputation: 163898
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.
Upvotes: 61
Reputation: 811
Your query is wrong.
remove all from $products = Product::all()
and then put get()
at the end of your query.
Upvotes: 0
Reputation: 4620
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.
Upvotes: 0