There are two ways you can implement this one is eloquent 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