S4boteur
S4boteur

Reputation: 145

Laravel return last users

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

Answers (3)

F1dzh
F1dzh

Reputation: 74

The simplest way could be :

$latestUsers = DB::table('users')->orderBy('id', 'desc')->limit(3)->get();

But I would prefer this method :

  1. You need to have a Users Model
  2. You need to import it inside the controller

then you should write this :

$latestUsers = User::orderBy('id','desc')->limit(3)->get();

or

 $latestUsers = User::latest()->limit(3)->get();

Upvotes: 0

Alexey Mezenin
Alexey Mezenin

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

Alex
Alex

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

Related Questions