Order by row and limit result in Laravel 5
38,459
Solution 1
You should use Fulls::orderBy(..)->take(5)->get()
instead.
Solution 2
If you want to sort/order a collection you can use the sortBy() method.
eg.
$full = Fulls::get(); // Get the Fulls collections
$full = $full->sortBy('count')->take(5);
Solution 3
You can skip for offset
$full = Fulls::orderBy('count', 'desc')->skip(0)->take(5)->get(); //get first 5 rows
$full = Fulls::orderBy('count', 'desc')->skip(5)->take(5)->get(); //get next 5 rows
Actual mysql query will look like:
SELECT * FROM fulls ORDER BY count DESC LIMIT 0,5
Author by
Avi
Updated on July 18, 2020Comments
-
Avi almost 4 years
I'm trying to get a result from the database in a laravel 5 based application and for the life of me can't figure it out.
I want to chose the top 5 results DESC from a row called count. This is what I have:
$full = Fulls::all()->orderBy('count', 'desc')->take(5)->get();
I tried plenty of other ways too but nothing seems to work. Now I'm getting an error:
FatalErrorException in indexController.php line 19: Call to undefined method Illuminate\Database\Eloquent\Collection::orderBy()
However, anywhere I look I see people working with
orderBy()
, so... what am I doing wrong?Thanks in advance...