Search code examples
laraveleloquentlaravel-relations

Laravel computed field on the relation's of a model like a model attribute


I have a model for Flights. The Flight have a relationship with payments_log.

In the payments_log table there are two fields: amount and type(Input/Output or add/sub).

I want to add a field on the Flight model for example Total_amount.

The total_amount on the Flight model will be a field that computed from relationship.

type   amount
I       5.0
I       10.0
O       2

Total_amount = I+I-O = 13

What is the best practice?


Solution

  • Create a accessor method on your Flight model that sums the amount column from the logs table:

    public function getTotalAmountAttribute()
    {
        // Sum log records of type I (add) 
        // and substract the sum of all log records of type ) (sub)
        return $this->paymentsLog()->where('type', 'I')->sum('amount') - $this->paymentsLog()->where('type', 'O')->sum('amount');
    }
    

    Then you can access it using:

    $flight->total_amount;