ehsanquddusi's avatar

Latest record from many to many relationship

I have two models, Advisory & User with a many to many relationship and one pivot table as advisory_table.

I am trying to return latest Advisory for a User from this many to many relation.

I have defined the relationship in User model as

public function latestAdvisory()
{
  return $this->belongsToMany(Advisory::class, 'advisory_users')
    ->latest()
    ->take(1);
}

It works fine with single record, but in the User collection, it loads this relation for the first record only. I tried to debug it and find the query generated by laravel. The query is

select `advisories`.*, `advisory_users`.`user_id` as `pivot_user_id`, `advisory_users`.`advisory_id` as `pivot_advisory_id` from `advisories` inner join `advisory_users` on `advisories`.`id` = `advisory_users`.`advisory_id` where `advisory_users`.`user_id` in (1, 22) order by `created_at` desc limit 1

I also tried to create an attribute and load the value in it, but it doesn't support eager loading and unnecessarily makes multiple db queries.

0 likes
5 replies
a4ashraf's avatar

@ehsanquddusi

why you are taking only one record from Advisory Model

you should change it like


public function latestAdvisory()
{
  return $this->belongsToMany(Advisory::class, 'advisory_users')
    ->latest();
}

// its will get all related records with order bt latest
quyle's avatar

if you want to get latest model of a M-M relationship on the fly, pass relationship name and created_at to latest() , i.e $user->posts()->latest('user_post.created_at')->first();

Snapey's avatar

@quyle your idea only works for a single result. No good if you want the latest post of all users

Please or to participate in this conversation.