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...
Laravel eloquent or query builder limt method do the same as limit MySQL function. It accepts one parameter as count( number of count). Model::limit(10); //or \DB::table('table_name')->limit(10); In the above syntax we have used 1 examples to show possibilities to use limit function.
To sort results in the database query, you'll need to use the orderBy() method, and provide the table field you want to use as criteria for ordering. This will give you more flexibility to build a query that will obtain only the results you need from the database.
all() is a static method on the Eloquent\Model. All it does is create a new query object and call get() on it. With all(), you cannot modify the query performed at all (except you can choose the columns to select by passing them as parameters). get() is a method on the Eloquent\Builder object.
You should use Fulls::orderBy(..)->take(5)->get()
instead.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With