I have a Model Review
that has a unix timestamp as 1 of it's attributes (table columns).
I use 2 accessors inside this model:
public function getReviewDateAttribute($value)
{
return strftime('%A %e %B %Y', $value);
}
public function getReviewDateIsoAttribute()
{
return Carbon::createFromTimestamp($this->review_date)->toDateTimeString();
}
getReviewDateAttribute
works as expected and shows up in the collection of models when I write a query.
However getReviewDateIsoAttribute
does not. What could be the reason for this?
A subquestion: If I use the same attribute in both functions, how can I use the original format as input value?
It is mean that these eloquent accessors and mutators methods allow us to alter the data before saving it to the database and get from the database. So in this tutorial, we will learn about eloquent accessors and mutators methods and how we can use them in the latest version of laravel 9.
Accessors, mutators, and attribute casting allow you to transform Eloquent attribute values when you retrieve or set them on model instances. For example, you may want to use the Laravel encrypter to encrypt a value while it is stored in the database, and then automatically decrypt the attribute when you access it on an Eloquent model.
I understand what you try to say, but Laravel accessors are "magic" functions that create attributes on the fly, hence this still should work. Please take a look at the documentation's getFullNameAttribute example.
- Laravel Daily Why use $appends with Accessors in Eloquent? Eloquent has a convenient feature called Accessors – you can define your own custom fields on top of existing in the database table. But then there’s an Eloquent property $appends – should we use it or not? And what’s the difference?
You should be adding it to the $appends
array. It isn't spinning through all available methods looking for getXXXXXAttribute
. The other one is used because it is an accessor for an actual attribute, this one is not an actual attribute.
class YourModel ....
{
protected $appends = ['review_date_iso'];
...
}
Laravel 5.5 Docs - Eloquent - Serialization - Appending Values to JSON
This is probably because ReviewDateIso
is not an actual column and therefore will not show up in the model collections...you can access it directly by calling the method directly
$model->getReviewDateIsoAttribute()
According to the docs accessors a ways of changing the value of a column before it is returned to the method that queried it.
If you want it to show up when you call the collection as Json append it to the output with
protected $appends = ['name_of_attribute'];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With