DolDurma
DolDurma

Reputation: 17303

Laravel return null for existing value in model

after getting query from database in Controller i have this output:

$newTickets = Ticket::with('user')->whereStatus(0)->orderBy('id', 'desc')->take(5)->get();

dd($newTickets[0]->user);

output:

#attributes: array:18 [▼
    "id" => 1
    "active" => 1
    "name" => "user1"
    "family" => "user1111"
    "username" => "xxxxx"
    "avatar" => "user_bg3.jpg"
    "email" => "[email protected]"
    "email_verified_at" => null
    "user_id" => null
    "properties_id" => null
    "password" => "$2y$10$b50fMYQMfMyJgtgCDEfQyueu.C.VfhfQCXT/f2Y8ObAe4nMrNiXEe"
    "mobile_number" => "333333"
    "device_id" => "0123456789"
    "api_token" => "aaaaaaa"
    "remember_token" => null
    "deleted_at" => null
    "created_at" => "2020-06-02 13:13:15"
    "updated_at" => "2020-06-02 13:13:15"
]

now when i try to show avatar field value, i'm getting null :|

dd($newTickets[0]->user->avatar);

output:

null

whats problem and why i can't get this value and that return null?

i can get another values and my problem is only getting avatar value

User model:

class User extends Authenticatable
{
    use Notifiable, SoftDeletes;

    protected $guarded = [
        'id',
    ];
    protected $hidden = [
        'password', 'remember_token',
    ];

    protected $casts = [
        'email_verified_at' => 'datetime',
        'avatar' => 'array',
    ];

    public function group()
    {
        return $this->belongsToMany(UserGroup::class, 'user_user_group');
    }

    public function child()
    {
        return $this->hasMany(User::class)->with('child');
    }

    public function parent()
    {
        return $this->belongsTo(User::class, 'user_id');
    }

    public function blogs()
    {
        return $this->hasMany(UserBlog::class);
    }

    public function setPasswordAttribute($password)
    {
        $this->attributes['password'] = Hash::make($password);
    }

    public function getFullNameAttribute()
    {
        return $this->name.' '.$this->family;
    }
}

Upvotes: 1

Views: 1470

Answers (1)

OMR
OMR

Reputation: 12188

you are casting avatar to an array ... when you do this ... laravel automatically decode 'avatar' from json for output and encode it for input ... more details

just remove avatar from :

  protected $casts = [
        'email_verified_at' => 'datetime',
        'avatar' => 'array',
    ];

Upvotes: 1

Related Questions