Select the first 10 rows - Laravel Eloquent

PhpOrmLaravelEloquent

Php Problem Overview


So far I have the following model:

class Listing extends Eloquent {
     //Class Logic HERE
}

I want a basic function that retrieves the first 10 rows of my table "listings" and passes them on to the view (via a controller?).

I know this a very basic task but I can't find a simple guide that actually explains step-by-step how to display a basic set of results, whilst detailing what is required in the model, controller and view files.

Php Solutions


Solution 1 - Php

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

Solution 2 - Php

The simplest way in laravel 5 is:

$listings=Listing::take(10)->get();

return view('view.name',compact('listings'));

Solution 3 - Php

Another way to do it is using a limit method:

Listing::limit(10)->get();

This can be useful if you're not trying to implement pagination, but for example, return 10 random rows from a table:

Listing::inRandomOrder()->limit(10)->get();

Solution 4 - Php

this worked as well IN LARAVEL 8

Model::query()->take(10)->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
QuestionJonnerzView Question on Stackoverflow
Solution 1 - PhpVit KosView Answer on Stackoverflow
Solution 2 - PhpLuca C.View Answer on Stackoverflow
Solution 3 - PhpAmadeView Answer on Stackoverflow
Solution 4 - Phpsaber tabatabaee yazdiView Answer on Stackoverflow