What is the best way to do calculation between attributes of a model, to display in the view?

0

I'm currently calculating everything in the view, something close to the below:

{{{ $object->a + ($object->b==1?5:10) + $object->c * (int)object->d... 

But it does not seem like a good idea. I do not want to save the calculated value in the database because I prefer to follow the normal forms.

    
asked by anonymous 12.04.2016 / 07:47

1 answer

0

Create methods with the return of the calculation in the model and pass the method to view through the controller.

Example:

No Model:

public static function calculo(Object $object) : float
{
    return $object->a + ($object->b == 1  ? 5: 10) + $object->c;
}

No Controller:

public function index()
{
    return view('caminho.nome.da.view', ['calculo' => NomeDoModel::calculo()] );
}

In View:

{{$ calculation}}

Remember:

Model only it knows business rule implementations, validation, verification and etc.

View only knows the data entry and exit .

Controller coordinates Model and View invoking methods, without knowing their implementations.

    
24.12.2018 / 16:31