How to customize the return of an attribute in Laravel?

3

In Laravel , I know that attributes can return an object of type Carbon\Carbon (an extension of DateTime of php), if the field is created_at or updated_at.

Example:

$usuario = Usuario::find(1);

// Não é uma string, é um Carbon\Carbon(object)
$usuario->created_at->format('d/m/Y');

But I'd like to do this with an attribute of type tinyint .

For example, in the Usuario model I have the attribute returned from the table named ativo .

Instead of returning 1 or 0 of the model, I'd like it to return "sim" or "não" .

Is it possible to do this in Laravel ?

    
asked by anonymous 15.03.2016 / 15:43

1 answer

3

You need to define an attribute using a Laravel feature called Eloquent Accessor , in which you define the name of the field, putting get at the beginning and attribute at the end.

They are called Model Accessors of Laravel .

So, do this in your model:

public function getAtivoTextoAttribute()
{
      return $this->attributes['ativo'] == 1 ? 'Sim' : 'Não';
}

Then, you just have to call:

$usuario = Usuario::find(1);

echo $usuario->ativo_texto;

In this case, I preferred to create an attribute with the name that does not collide with the actual table name, as I believe this is the best way to work.

If you optionally want, when you return the query in json , this "custom field" appears, just do so:

class Usuario
{
      protected $appends = ['ativo_texto']

      public function getAtivoTextoAttribute(){ /* definição */ }
}
    
15.03.2016 / 16:42