Update with Addition and Subtraction Laravel?

1

I'm starting to learn how to use Framework Laravel 5.4 so I'm doing a personal finance system and I have a Conta table with the field ( Saldo );

I would like to make a Credit or Debit transaction that will Subtract or Sum Saldo with transaction value .

I know how to do this in SQL, but what is the best way to do this in Laravel?

    
asked by anonymous 31.08.2017 / 04:41

1 answer

1

There are two ways you can implement this one is ORM Model and the other Database: Query Builder

Create a class to represent your table as follows:

<?php namespace App\Models;

use Illuminate\Database\Eloquent\Model;    
class Conta extends Model
{
    protected $table = 'conta';
    protected $fillable = ['cliente_id','saldo'];
    public $timestamps = false;    

    public function setSomaSaldo($saldo)
    {
        // Conta Existente
        if ($this->exists)
        {
            $this->attributes['saldo'] =
                $this->attributes['saldo'] + $saldo;
            $this->save();
        }
        return $this;
    }

    public function setSubtrairSaldo($saldo)
    {
        // Conta Existente
        if ($this->exists)
        {
            $this->attributes['saldo'] =
                $this->attributes['saldo'] - $saldo;
            $this->save();
        }
        return $this;
    }
}

which will contain two methods one to add balance and the other to subtract the balance, following the account exists for these two methods to work. To use the do methods:

  • Adding :

    $client_id = 1;
    $saldo = 150.69;
    $d = App\Models\Conta::where('cliente_id', $client_id)->first();
    if ($d) 
    {
        $d->setSomaSaldo($saldo);
    }
    
  • Subtracting :

    $client_id = 1;
    $saldo = 150.69;
    $d = App\Models\Conta::where('cliente_id', $client_id)->first();
    if ($d) 
    {
        $d->setSubtrairSaldo($saldo);
    }
    

In this method setSomaSaldo($saldo) will aggregate the value and then save the change in the table, and this also happens in setSubtrairSaldo($saldo) that subtract the value of the current balance and saves the changes.

By the increment / decrement method you can add or subtract by Query Builder simply and with excellent performance:

  • Adding :

    $client_id = 1;
    $saldo = 150.69;
    $status = \DB::table('conta')
           ->where('cliente_id',$client_id)
           ->increment('saldo', $saldo);
    if ($status) // atualizado com sucesso
    {
    }
    
  • Subtracting :

    $client_id = 1;
    $saldo = 150.69;
    $status = \DB::table('conta')
           ->where('cliente_id',$client_id)
           ->decrement('saldo', $saldo);
    if ($status) // atualizado com sucesso
    {
    }
    

Note: here also works class

31.08.2017 / 17:41