Reputation: 145
I was wondering, what is the simplest way to return last 3 users from database and show them in homepage with Laravel Framework. I have this column, last three registred users/companies and i want to show users name and more info.
Upvotes: 1
Views: 69
Reputation: 74
The simplest way could be :
$latestUsers = DB::table('users')->orderBy('id', 'desc')->limit(3)->get();
But I would prefer this method :
then you should write this :
$latestUsers = User::orderBy('id','desc')->limit(3)->get();
or
$latestUsers = User::latest()->limit(3)->get();
Upvotes: 0
Reputation: 163938
Use latest()
and take()
methods:
User::latest()->take(3)->get();
latest()
is a shortcut for orderBy('created_at', 'desc')
, so you also can do this:
User::orderBy('created_at', 'desc')->take(3)->get();
Upvotes: 2
Reputation: 1418
I would do a scope in the User model :
public function scopeLast($query){
return $query->orderBy('id', 'DESC')->limit(3);
}
Considering that id is auto-incremented, if not, use the created_at column instead of the id column inside the orderBy
Use it like this :
User::last()->get();
Upvotes: 1