Add attribute to appends from trait

Niccolò Meloni
Jan 17, 2019 · 1 min read

The $appends property of an Eloquent model contains attributes that do not have a corresponding column in your database.

Today I’m going to show you how to add an attribute to $appends property from a trait.

Create a trait

Let’s create a trait aimed to append an attribute to an Eloquent model.

trait AppendAttributeTrait
{
public function initializeAppendAttributeTrait()
{
$this->append('appended_property');
}
public function getAppendedPropertyAttribute()
{
return '...';
}
}

By design, the initializeAppendAttributeTrait method will be called dynamically on the Eloquent model instance. So $this represents the Eloquent model instance that will use AppendAttributeTrait. Note the naming convention: initializeX method for a trait named X.

Use trait

Let’s go to use AppendAttributeTrait from an Eloquent model.

class MyModel extends Illuminate\Database\Eloquent\Model
{
use AppendAttributeTrait;
/* ... */
}

Serialize the model

Now, each time you will serialize an instance of MyModel Eloquent model, you’ll get the appended_property in the serialized output.

{ appended_property: '...' }

Ok, take care.

Laravel is the way!

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade