From 433710afe1a710ff171a7d06e941dae63dced76a Mon Sep 17 00:00:00 2001 From: Muhammad Sulaiman Yusuf Date: Wed, 20 Jul 2022 00:20:44 +0700 Subject: [PATCH] move calculations to model --- app/Models/ReportActivityMaterial.php | 41 ++++++++++++++++++++++----- 1 file changed, 34 insertions(+), 7 deletions(-) diff --git a/app/Models/ReportActivityMaterial.php b/app/Models/ReportActivityMaterial.php index 4c455ee..1549248 100644 --- a/app/Models/ReportActivityMaterial.php +++ b/app/Models/ReportActivityMaterial.php @@ -3,16 +3,43 @@ namespace App\Models; use Illuminate\Database\Eloquent\Model; +use App\Models\Activity; +use App\Models\AssignMaterial; class ReportActivityMaterial extends Model { - protected $table = 'report_activity_material'; + protected $table = 'report_activity_material'; - const CREATED_AT = 'created_at'; - const UPDATED_AT = 'updated_at'; + const CREATED_AT = 'created_at'; + const UPDATED_AT = 'updated_at'; - protected $fillable = [ - 'activity_id', 'user_id', 'qty', 'lat', 'lon','assign_material_id', - 'report_date', 'description', 'created_at', 'created_by', 'updated_at', 'updated_by' - ]; + protected $fillable = [ + 'activity_id', 'user_id', 'qty', 'lat', 'lon','assign_material_id', + 'report_date', 'description', 'created_at', 'created_by', 'updated_at', 'updated_by' + ]; + + public static function boot() { + parent::boot(); + + static::created(function($data) { + + $activity = Activity::find($data->activity_id); + $assignedMaterial = AssignMaterial::find($data->assign_material_id); + + $activity->biaya_actual += floatval($assignedMaterial->budget) * floatval($data->qty); + $activity->save(); + + }); + + static::deleted(function($data) { + + $activity = Activity::find($data->activity_id); + $assignedMaterial = AssignMaterial::find($data->assign_material_id); + + $activity->biaya_actual -= floatval($assignedMaterial->budget) * floatval($data->qty); + $activity->save(); + + }); + + } }