Laravel 10: Appending Values To Model
1 min readJul 24, 2023
Set up the relationship
Our Post model has many comments
use Illuminate\Database\Eloquent\Relations\HasMany;
class Post extends Model
{
/**
* A Post has many comments
* @return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function comments(): HasMany
{
return $this->hasMany(Comment::class);
}
}
Until now there is nothing new, what comes next is what I was talking about. Let’s create an accessor that will return the count of comments related to the current Post.
/**
* Count comments of posts
*/
protected function countComments(): Attribute
{
return new Attribute(
get: fn () => $this->comments()->count()
);
}
Append the value to the Model
So what we will do now is simple, we want to get the count_comments with the Post object once we grab it. it's as simple as adding the name of the attribute in the appends array.
/**
* The accessors to append to the model's array form.
*
* @var array
*/
protected $appends = ['count_comments'];
Appending At Run Time
return $post->append('count_comments')->toArray();