145

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

 SELECT * FROM  `games` LIMIT 30 , 30 

And with Eloquent ?

William Perron
  • 485
  • 7
  • 16
Natan Shalva
  • 1,572
  • 2
  • 11
  • 11

4 Answers4

254

Create a Game model which extends Eloquent and use this:

Game::take(30)->skip(30)->get();

take() here will get 30 records and skip() here will offset to 30 records.


In recent Laravel versions you can also use:

Game::limit(30)->offset(30)->get();
Muhammad Usman
  • 12,439
  • 6
  • 36
  • 59
  • may i ask you to take a look at a Laravel ORM related question here : https://stackoverflow.com/questions/59956706/laravel-randomly-select-n-number-of-rows-containing-same-value-in-certain-colu ? – Istiaque Ahmed Jan 28 '20 at 20:49
20

We can use LIMIT like bellow:

Model::take(20)->get();
  • Looks like you're using take and not limit – twigg Jan 17 '19 at 10:55
  • 3
    In this case, `take` is just an alias to `limit`. See https://github.com/laravel/framework/blob/5.7/src/Illuminate/Database/Query/Builder.php#L1896. – Xartrick Jan 21 '19 at 18:47
19

If you're looking to paginate results, use the integrated paginator, it works great!

$games = Game::paginate(30);
// $games->results = the 30 you asked for
// $games->links() = the links to next, previous, etc pages
fregante
  • 29,050
  • 14
  • 119
  • 159
  • 6
    This is seriously amazing! Using bootstrap, literally all the code you need is $games = Game::paginate(30) in your controller and {{ $games->links() }} in your view... it takes care of everything. Loving Laravel! – david_nash Feb 08 '17 at 02:26
0

Also, we can use it following ways

To get only first

 $cat_details = DB::table('an_category')->where('slug', 'people')->first();

To get by limit and offset

$top_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(0)->orderBy('id', 'DESC')->get();
$remaining_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(30)->orderBy('id', 'DESC')->get();