O
O
ObehanProger2020-05-11 11:02:47
Laravel
ObehanProger, 2020-05-11 11:02:47

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();
  }
}

When called , it $chat->messageCountthrows an error:
App\Chat::messageCount must return a relationship instance.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ilya, 2020-05-11
@ObehanProger

public function getMessageCountAttribute(){
    return $this->messages()->count();
}

Laravarl Accessors
Just keep in mind that the so-called. eager loading in this way will not work.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question