Ad

Laravel Eloquent: Should I Append Values From The Model Or Controller?

I have a model with id, name, and cost.

protected $table = 'has_costs';
protected $fillable = [
    'id','name','cost'
];

Then I also used append to add new columns, cost_under and cost_over, which basically does simple calculation from cost.

protected $appends = ['cost_over','cost_under'];

Should I do the calculation in the model like this:

public function getCostOverAttribute()
{
    $costOver = (20/100)*cost;
    return $this->attributes['over'] = $costOver;
}

public function getCostUnderAttribute()
{
    $costUnder = (80/100)*cost;
    return $this->attributes['under'] = $costUndr;
}

Or should I still do it in the controller to keep it more "MVC"?

The actual code is more complex than this example and it takes a lot of time thinking about how to append each values deep inside complex Eloquent with queries.

Ad

Answer

Makes more sense to add cost_overand cost_under as model properties.

public function getCostOverAttribute()
{
    return 20 / 100 * $this->cost;
}

public function getCostUnderAttribute()
{
    return 80 / 100 * $this->cost;
}

You can access them $model->cost_over and $model->cost_under.

Keep your controller clean from internal model's calculations over its data.

Also if you don't want to append these properties each time you instance the model, you can append attributes on the way as $model->append('cost_over') in your controller.

Ad
source: stackoverflow.com
Ad