I am trying to build some chat system using Laravel and i have these 2 models: User and Thread
The User model has Messagable Trait where you can get all the threads with
$user->threads();
I am trying to eager load additional data to the threads array using the following:
$threads = Auth::user()->threads()->with(['participants.user'])->get();
What i am struggling is the Threads model has function to get the latest message from it:
$thread->getLatestMessage();
My question is how can i append this latest message to the upper query i am doing. I was trying something like this but its not ok... I guess im doing something stupid here...
$threads = Auth::user()->threads()->with([
'participants.user',
'latestMessage' => function ($query) {
return $query->getLatestMessageAttribute();
}])->get();
or
$threads = Auth::user()->threads()->with(['participants.user','getLatestMessageAttribute'])->get();
I hope i clarified this ok because i am using a 3rd party package for this system which has these Traits and Thread classes i am using.
SOLUTION
Looks like i had to add append('accessor_name') at the end when getting the collection.
$collection = Auth::user()->relationship()->get()->append('accessor_name');