public static function boot() { parent::boot(); // Setup event bindings... Balance::saving(function ($balance) { $balance->user_id = Auth::id(); return $balance; }); $user_id = Auth::id(); $balance = Balance::where('user_id', $user_id)->orderBy('id', 'DESC')->first(); if (count($balance) > 0) { $date = Carbon::createFromFormat('Y-m-d H:i:s', $balance->created_at); if ($date->isToday()) { // Deixa como está. } else { // Cria o pro=imeiro registro $todayAmount = DB::table('transactions')->where('created_at', '>', date("Y-m-d") . " 00:00:00")->where('created_at', '<=', date('Y-m-d H:i:s'))->where('user_id', Auth::id())->where('done', 1)->sum('amount'); $newAmount = $balance->amount + $todayAmount; // Cria um novo pro dia de hoje $balance = Balance::create(['amount' => $newAmount, 'user_id' => $user_id]); } } else { // Cria o pro=imeiro registro $amount = DB::table('transactions')->where('created_at', '<=', date('Y-m-d H:i:s'))->where('user_id', Auth::id())->where('done', 1)->sum('amount'); $balance = Balance::create(['amount' => $amount, 'user_id' => $user_id]); } }
public function update_balance() { $pre_total = self::earlier_than($this)->first(); // $pre_balance = self::earlier_than($this)->where('account_id', '=', $this->account_id)->first(); $pre_balance = self::earlier_than($this)->where_account_id($this->account_id)->first(); $total = 0; if (is_null($pre_total)) { $total = $this->amount; } else { $total = $pre_total->balance->total_amount + $this->amount; } $balance = 0; if (is_null($pre_balance)) { $balance = $this->amount; } else { $balance = $pre_balance->balance->balance_amount + $this->amount; } $b = $this->balance; if (is_null($b)) { $b = Balance::create(array('balance_amount' => $balance, 'balance_currency' => $this->currency, 'total_amount' => $total, 'total_currency' => $this->currency, 'transaction_id' => $this->id)); } else { $b->balance_amount = $balance; $b->balance_currency = $this->currency; $b->total_amount = $total; $b->total_currency = $this->currency; $b->save(); } $this->update_later_balance(); }