Home > other >  How to include model attribute automatically?
How to include model attribute automatically?

Time:05-06

I have the User model which define the following attribute:

public function getAvatarUrlAttribute()
{    
    return 'https://i.pravatar.cc/300?u=' . $this->email;
}

I usually access to this attribute using something like:

User::find(1)->avatar_url;

Problem

I need to return all the attributes of the User model when I execute this code:

$users = User::whereRoleIs('doctor')->get();

The collection returned to ajax doesn't contain avatar_url attribute though. How can I include all the attributes automatically?

Thanks.

CodePudding user response:

You need to explicitly tell Laravel that you want to include it when you convert it to an array using appends:

<?php

class User {

    protected $appends = ['avatar_url'];

    public function getAvatarUrlAttribute()
    {    
        return 'https://i.pravatar.cc/300?u=' . $this->email;
    }

}
  • Related