Answer the question
In order to leave comments, you need to log in
How to add a property to an Eloquent model?
There are two related models Chat and Message. How to add a messageCount property to the Chat model that calculates the number of messages in the chat. You need to access the property directly in Chat, and not through Messages ($chat->messages->count()):
class Chat extends Model
{
public function messages(){
return $this->hasMany(Message::class);
}
public function messageCount(){
return $this->messages()->count();
}
}
$chat->messageCount
throws an error:App\Chat::messageCount must return a relationship instance.
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question