Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

amitsolanki24_'s avatar

Fetch user with last notification order by notification

How can I fetch user with last notification order by last notification created at using laravel relationship.

#user model
public function last_notification(): HasOne
{
  return $this->hasOne(Notification::class, 'sender_id', 'id')
       ->latest()
       ->take(1);
}

#code

$users_with_lastest_notification = User::has('latest_notification')
      ->with('latest_notification')
      ->latest()
      ->get();

Above code give me users data in descending order but I want users data in descending order according to latest notification created at date.

0 likes
3 replies
tykus's avatar

Use a JOIN rather than using the relationship method for the ordering, e.g.

$users_with_lastest_notification = User::with('latest_notification')
    ->select('users.*) // only want user fields in User model instances
    ->join('notifications', 'notifications.user_id', 'users.id')
    ->orderByDesc('notifications.created_at')
    ->get();

Aside, you can redefine the relationship using the one-of-many approach:

public function last_notification(): HasOne
{
  return $this->hasOne(Notification::class, 'sender_id', 'id')->latestOfMany();
}

https://laravel.com/docs/11.x/eloquent-relationships#has-one-of-many

1 like
kevinbui's avatar

I would do two things:

  • Use this subquery to order users by their last notifications.
  • the same with @tykus, eager load the last notification for each user by with that last_notification relationship.

Pls let me know if you need me to elaborate.

Please or to participate in this conversation.