How to recover calculated fields in Laravel?

Asked

Viewed 88 times

0

My Edit controller

$tipos     = TituloTipo::all();
$devedores = Devedor::all();
$clientes  = Cliente::all();
$divida    = Divida::find($id);

return view('admin.dividas.edit',compact('divida','devedores','clientes', 'tipos'  ));

In the Debt table I need that whenever the user edit, preview the total_corrected field be updated to a simple interest formula. total_corrected = value x interest x months

  • total_corrigido is a field of your table? if yes with events you can solve this...

2 answers

1


The best way is to use an accessor

https://laravel.com/docs/5.8/eloquent-mutators#Defining-an-accessor

class Divida extends Model
{
    /**
     * obter total da dívida.
     *
     * @return float
     */
    public function getTotalCorrigidoAttribute()
    {
        return $this->valor_divida x $this->juros x $this->meses;
    }
}

$divida  = Divida::find($id);

//view

<p>O valor da dívida é {{$divida->total_corrigido}}</p>

1

At first, what you need to do is retrieve the specific field of your model:

$tipos     = TituloTipo::all();
$devedores = Devedor::all();
$clientes  = Cliente::all();
$divida    = Divida::find($id);
$dividaAtualizada = $divida['valor_divida'] * $juros * date_diff(date_create(date('m')), date_create($data_ini))->format('%d');
return view('admin.dividas.edit',compact('divida','devedores','clientes', 'tipos', 'dividaAtualizada'  ));

I recommend that the calculation be done through a function. the $data_ini variable you will need to see how it will recover from your database (by the format as it was registered, etc).

Browser other questions tagged

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