Jamie Jamie - 4 years ago 98
PHP Question

Laravel query latest record

I've this query:

I'm building a forum and I would like to show the latest message that has being posted. I'm doing that like this:

return Forum::with(['users' => function($query){
$query->select('user.id', 'user.name', 'user.last_name')

forum model:

* @return mixed
public function users()
return $this->belongsToMany(User::class, 'message');

How do I only receive the latest user. Right now I receive them all.

Thanks a lot!

Answer Source
public function users()
    return $this->belongsToMany(User::class, 'message')->orderBy('id', 'desc');

If you want to limit the number of users returned, append ->take(10); to take only last 10 users

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download