Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by row and limit result in Laravel 5

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...

like image 263
Avi Avatar asked Mar 26 '15 10:03

Avi


People also ask

How do I limit query results in laravel?

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.

How to order query in laravel?

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.

What is all () in laravel?

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.


2 Answers

You should use Fulls::orderBy(..)->take(5)->get() instead.

like image 86
David Kmenta Avatar answered Oct 05 '22 22:10

David Kmenta


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
like image 29
Ankit Jindal Avatar answered Oct 06 '22 00:10

Ankit Jindal