How to customize the return of an attribute in Laravel?

Asked

Viewed 635 times

3

In the Laravel, i know that attributes can return an object of type Carbon\Carbon (an extension of DateTime 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 would like to do this with an attribute like tinyint.

For example, in the model Usuario i have returned attribute from table called ativo.

Instead of returning 1 or 0 model, I wish she’d already return to me "sim" or "não".

It is possible to do this in the Laravel?

1 answer

3


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

Are the so-called Model Accessors of Laravel.

So do it like this on your model:

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

Then you just make the call:

$usuario = Usuario::find(1);

echo $usuario->ativo_texto;

In this case, I preferred to create an attribute with the name that does not conflict with the real name of the table, because I believe this is the best way to work.

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

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

      public function getAtivoTextoAttribute(){ /* definição */ }
}
  • 2

    A link to documentation and use the name of this resource would be more interesting. atributo método mágico can generate confusion with the __get of PHP.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.