Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select the first 10 rows - Laravel Eloquent

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.

like image 261
Jonnerz Avatar asked Jan 21 '14 10:01

Jonnerz


People also ask

How do I get the latest 10 record in Laravel?

If you give latest() or oldest() a date column other than created_at, it will order by that column instead. $chatMessage = ChatMessage::with('user. role') ->oldest('updated_at') ->limit(10) ->toSql();

What is first () in eloquent?

The Laravel Eloquent first() method will help us to return the first record found from the database while the Laravel Eloquent firstOrFail() will abort if no record is found in your query. So if you need to abort the process if no record is found you need the firstOrFail() method on Laravel Eloquent.

How do you pluck in Laravel eloquent?

While developing in eloquent, the column name can be passed as an argument in order to extract the values. Pluck () also accepts a second argument and if it happens to be an Eloquent collection, it will be another column name. To further strengthen the pluck() function, the wherein() function can be used.

What does First () return in Laravel?

It just returns null.


3 Answers

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
like image 127
Vit Kos Avatar answered Oct 18 '22 02:10

Vit Kos


The simplest way in laravel 5 is:

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

return view('view.name',compact('listings'));
like image 27
Luca C. Avatar answered Oct 18 '22 02:10

Luca C.


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();
like image 26
Amade Avatar answered Oct 18 '22 02:10

Amade