Avi
Avi

Reputation: 798

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?

Upvotes: 13

Views: 49973

Answers (5)

Nageen
Nageen

Reputation: 1759

You can use skip and take function of laravel and orderBy

Fulls::where([['user_id','=',auth()->user()->id]])
    ->where([['title','LIKE',"%".$text_val."%"]])
    ->orderBy('id','DESC')
    ->skip($offset)
    ->take(2);

Upvotes: 0

ilius Sagar
ilius Sagar

Reputation: 1

The code you've written has a logical issue because you are chaining Eloquent methods incorrectly. The orderBy and take methods should be used before the get method. The get method retrieves the results and ends the query building process.

$full = Fulls::orderBy('count', 'desc')->take(5)->get();

Upvotes: 0

Ankit Jindal
Ankit Jindal

Reputation: 4030

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

Upvotes: 1

Thomas Negash
Thomas Negash

Reputation: 461

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); 

Upvotes: 4

David Kmenta
David Kmenta

Reputation: 850

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

Upvotes: 29

Related Questions