As I have been following Eloquent Performance Patterns by Jonathan Reinink, he has explained how to add dynamic relationship using subquery for models with hasmany relationship. But as per my application I need to do the same for belongstomany relationship. Please help me achieve it.
Here is the example source code of the following, which achieves the said above dynamic relationship using subquery for models with hasmany relationship.
$query = User::query()
->addSelect(['role' => Role::select('name')
->whereColumn('user_id', 'users.id')
->latest()
->take(1)
]);
return $this->applySorting($query);