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

MysqlLaravelEloquentSql Limit

Mysql Problem Overview


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

 SELECT * FROM  `games` LIMIT 30 , 30 

And with Eloquent ?

Mysql Solutions


Solution 1 - Mysql

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

Solution 2 - Mysql

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

Solution 3 - Mysql

We can use LIMIT like bellow:

Model::take(20)->get();

Solution 4 - Mysql

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNatan ShalvaView Question on Stackoverflow
Solution 1 - MysqlMuhammad UsmanView Answer on Stackoverflow
Solution 2 - MysqlfreganteView Answer on Stackoverflow
Solution 3 - MysqlMd. Saidur Rahman MilonView Answer on Stackoverflow
Solution 4 - MysqlKrishnamoorthy AcharyaView Answer on Stackoverflow