Laravel 9 Mutator - Custom field Hi guys.
On Laravel 9, how can I create something like "dateForHumans" custom attribute?
On Laravel 8 I do that:
public function getDateForHumansAttribute()
{
...
}
On Laravel 9 I try:
On Laravel 8 I do that (and not work):
public function dateForHumans(): Attribute
{
return new Attribute::make( get: fn($this->date) => date('d/m/Y', $this->date) );
}
Obs.: in my case is not just format the date ok? I know I can use casts for that. The main question is about to how to create custom fields/attributes .
The Laravel 8 syntax still works in Laravel 9 as well.
In Laravel 9 there's a new syntax support as you mentioned but with new keyword
public function dateForHumans(): Attribute
{
return Attribute::make( get: fn($this->date) => date('d/m/Y', $this->date) );
}
@MohamedTammam This not work for me. Just return empty.
That's my code:
public function dataForHumans(): Attribute
{
$correctValue = $this->periodo == 'month'
? date('m/Y', strtotime($this->data))
: date('d/m/Y', strtotime($this->data));
return Attribute::make(get: fn($correctValue) => $correctValue);
}
@patrickmaciel try: $model->data_for_humans
On the first example the docs says:
In this example, we'll define an accessor for the first_name attribute.
and then the example code below it defines a firstName(): Attribute method.
https://laravel.com/docs/9.x/eloquent-mutators#defining-an-accessor
Also the previous way of defining accessors/mutators also still work, but like the same you would define:
public function getDateForHumansAttribute()
{
// accessor code here
}
And called it like:
$model->date_for_humans;
Note I preserved date_for_humans and date_for_humans according to each code sample you sent.
@patrickmaciel It should be
public function dataForHumans(): Attribute
{
$correctValue = $this->periodo == 'month'
? date('m/Y', strtotime($this->data))
: date('d/m/Y', strtotime($this->data));
return Attribute::make(get: fn($value) => $correctValue);
}
But personally for this example I prefer the old way.
public function getDataForHumans()
{
$correctValue = $this->periodo == 'month'
? date('m/Y', strtotime($this->data))
: date('d/m/Y', strtotime($this->data));
return $correctValue;
}
@rodrigo.pedra i wll try that.
Related to the old way to do that, I don't want to use that. I think if they provide a new way, I need to use that (as a good practice).
@patrickmaciel you are sure right.
The previous way is not even documented anymore. But sometimes is good to know when working on legacy projects
Please sign in or create an account to participate in this conversation.