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');
You can override class .Create new model and extend package model
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Thread extends \Lexx\ChatMessenger\Models\Thread
{
use HasFactory;
protected $appends=['latest_message'];
}
Publish config:
php artisan vendor:publish --provider="Lexx\ChatMessenger\ChatMessengerServiceProvider" --tag="config"
in config/chatmessenger.php
'thread_model' => \App\Models\Thread::class,
Updated If anyone still not getting get attribute data then dont forget to clear cache
php artisan cache:clear
php artisan optimize
php artisan config:clear
php artisan clear