Select the first 10 rows - Laravel Eloquent
Solution 1:
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:
- pagination docs
- passing data to views
- Eloquent basic usage
- A cheat sheet
Solution 2:
The simplest way in laravel 5 is:
$listings=Listing::take(10)->get();
return view('view.name',compact('listings'));
Solution 3:
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:
this worked as well IN LARAVEL 8
Model::query()->take(10)->get();