where(function ($query) use ($attributes, $searchTerm) { foreach ($attributes as $attribute) { $query->when( str_contains($attribute, '.'), function ($query) use ($attribute, $searchTerm) { [$relationName, $relationAttribute] = explode('.', $attribute); $query->orWhereHas($relationName, function ($query) use ($relationAttribute, $searchTerm) { $query->where($relationAttribute, 'LIKE', "%{$searchTerm}%"); }); }, function ($query) use ($attribute, $searchTerm) { $query->orWhere($attribute, 'LIKE', "%{$searchTerm}%"); } ); } }); } public function labourOrder() { return $this->belongsTo(LabourOrder::class, 'lo_id'); } public function project() { return $this->belongsTo(LabourOrder::class); } public function payments() { return $this->belongsToMany(Payment::class, $this->paymentPivotTable)->withPivot('payment_amount'); } public function scopeOpen($q) { return $q->where('status', 'OPEN'); } /** * @param Builder $q * @param mixed|null $exceptPaymentId menjumlahkan total payment kecuali id yang dipassing * @return Builder */ public function scopeUnpaid($q, $exceptPaymentId = null) { return $q->where(function ($q) use ($exceptPaymentId) { return $q->whereStatus('OPEN')->whereRaw( " CAST(amount AS SIGNED) > ( COALESCE ( ( SELECT CAST( SUM(payment_amount) AS SIGNED ) FROM {$this->paymentPivotTable} WHERE bill_labour_order_id=id ". ($exceptPaymentId ? "AND payment_id != {$exceptPaymentId}" : "") ." ) , 0) ) " ); }); } public function scopePaid($q) { return $q->where(function ($q) { return $q->whereStatus('PAID')->whereRaw( " CAST(amount AS SIGNED) <= ( COALESCE ( ( SELECT CAST( SUM(payment_amount) AS SIGNED ) FROM {$this->paymentPivotTable} WHERE bill_labour_order_id=id ) , 0) ) " ); }); } public function getPaymentAmountAttribute() { return $this->payments()->sum("payment_amount"); } public function getAmountDueAttribute() { return max(0, $this->amount - $this->paymentAmount); } public function getCurrentStatusAttribute() { if (count($this->payments) > 0) { if ($this->amount_due <= 0) { return "paid"; } return "partially paid"; } return $this->status; } }