0

In my Laravel project I am preforming a database query where I search through my media table and grab all results that belong to a user_id. The results are ordered by most votes in descending order. However, this returns all the users images. I only want to grab the first 4 results, not all. How can this be done?

My media table looks like this.

| id | user_id | url | votes |

My controller looks like this

public function getUserImagesByVote($user_id)
{

    return Media::where('user_id', $user_id)->orderBy('votes', 'DESC')->get();
}
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284
xslibx
  • 4,249
  • 9
  • 35
  • 52
  • possible duplicate of [Is there a way to "limit" the result with ELOQUENT ORM of Laravel?](http://stackoverflow.com/questions/15229303/is-there-a-way-to-limit-the-result-with-eloquent-orm-of-laravel) – Burhan Khalid Feb 04 '15 at 04:36

2 Answers2

2

As mentioned in laravel docs, you can use take() to limit the result and skip() to offset

Offset & Limit

$users = DB::table('users')->skip(10)->take(5)->get();

in your case use this query

Media::where('user_id', $user_id)->take(4)->orderBy('votes', 'DESC')->get()
Community
  • 1
  • 1
Saqueib
  • 3,484
  • 3
  • 33
  • 56
0

you could use take() for it. I believe "Media::where('user_id', $user_id)->orderBy('votes', 'DESC')->take(4)->get();" will help. You have take() and skip() provided by lavarvel. Hope this helps.