Mahmoud Al-HabashOpen to new projects
  • WorkWork
  • ServicesServices
  • LabLab
  • WritingWriting
  • ContactContact
Amman--:--عربي
Writing/Laravel

Laravel Eloquent: Virtual Attributes

Add computed attributes to your Eloquent models.

16 January 20261 min readLaravelاقرأ بالعربية

On this page

  1. Define Accessor
  2. Append to Array
  3. Append Dynamically
  4. Hide from Array

Virtual attributes:

Define Accessor

php
protected function fullName(): Attribute
{
    return Attribute::make(
        get: fn () => $this->first_name . ' ' . $this->last_name,
    );
}

Append to Array

php
protected $appends = ['full_name'];

Append Dynamically

php
$user->append('full_name');
$users = User::all()->append('full_name');

Hide from Array

php
protected $hidden = ['password', 'remember_token'];

$user->makeHidden('email');
$user->makeVisible('password');
All articles

Keep reading

  • Laravel Action Classes Pattern16 January 20261 min read
  • Laravel Action Classes: Single Responsibility16 January 20261 min read
  • Laravel API Rate Limiting16 January 20261 min read