Walter Gandarella
Walter Gandarella

Reputation: 838

How to Eloquent not persist certain attributes in the table?

I have a model with table attributes: protein, carbohydrate and fat. I want to add the model an attribute 'calorie' which must be calculated based on the previous three standing on the table, however this 'calorie' is not to be persisted. My doubt is whether the Eloquent does it automatically verifies that the field is not in the table or I have to inform in any way? In other languages I would use a annotation to inform you that should not persist this attribute, but Eloquent simply ignores any attribute that is not on the table fly away When I print the output of a model.

class Alimento extends Model
{

    const CALORIA_PROTEINA = 4;
    const CALORIA_CARBOIDRATO = 4;
    const CALORIA_GORDURA = 9;

    protected $table = "alimentos";
    protected $fillable = ["nome", "proteina", "gordura", "carboidrato", "tabela", "forte"];

    public $timestamps = false;
    public $caloria = 0; // <= This is an attribute that should not be persisted
    public $qtde = 100; // <= This is an attribute that should not be persisted

    public static $rules = [
        "nome" => "required",
    ];

    public function calculaCaloria()
    {
        if ($this->qtde == 100) {
            $this->caloria = ($this->proteina * self::CALORIA_PROTEINA) +
                ($this->carboidrato * self::CALORIA_CARBOIDRATO) +
                ($this->gordura * self::CALORIA_GORDURA);
        } else {
            $this->caloria = $this->regraDeTres($this->proteina * self::CALORIA_PROTEINA) +
                $this->regraDeTres($this->carboidrato * self::CALORIA_CARBOIDRATO) +
                $this->regraDeTres($this->gordura * self::CALORIA_GORDURA);
        }
    }

    private function regraDeTres($_valor)
    {
        return ($_valor * $this->qtde) / 100;
    }

}

And in my test controller I do this:

public function novoAlimento()
    {
        $al = new Alimento();
        $al->nome = "Teste";
        $al->proteina = 20;
        $al->carboidrato = 15;
        $al->gordura = 8;
        $al->qtde = 50;
        $al->forte = "C";

        $al->calculaCaloria();

        $al->save();
        return $al;
    }

And this is my controller's return:

{"nome":"Teste","proteina":20,"carboidrato":15,"gordura":8,"forte":"C"}

Thanks!

Upvotes: 1

Views: 205

Answers (1)

huuuk
huuuk

Reputation: 4795

You want to place caloria property into returned JSON?
Try to override toArray() method

public function toArray()
{
   $array = parent::toArray();
   $this->calculaCaloria();
   $array['caloria'] = $this->caloria;
   return $array;
}

Upvotes: 1

Related Questions