72

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.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101
Jonnerz
  • 1,111
  • 2
  • 11
  • 16

5 Answers5

155

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:

Ruitjes
  • 29
  • 7
Vit Kos
  • 5,535
  • 5
  • 44
  • 58
29

The simplest way in laravel 5 is:

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

return view('view.name',compact('listings'));
Luca C.
  • 11,714
  • 1
  • 86
  • 77
26

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();
Amade
  • 3,665
  • 2
  • 26
  • 54
7

this worked as well IN LARAVEL 8 and 9 and 10 and above

Model::query()->take(10)->get();
saber tabatabaee yazdi
  • 4,404
  • 3
  • 42
  • 58
0

This also worked in Laravel 9

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