A S M Saief
A S M Saief

Reputation: 310

How to get Sum from relationship in laravel

//Client Model

protected $fillable = [
        'client_name', 'plan_id', 'client_type'
    ];

public function plan(){
        return $this->belongsTo(Plan::class, 'plan_id', 'id');
    }

// Plan Model

protected $fillable = [
        'price'
    ];

public function clients()
    {
        return $this->hasMany(Client::class);
    }

I want to get total price of all clients where client_type = something

Upvotes: 0

Views: 40

Answers (1)

namelivia
namelivia

Reputation: 2735

I would do it like this:

function getClientTypeTotal($clientType)
{
    return Client::where('client_type', $clientType)->get()->sum(function ($client) {
        return $client->plan->price;
    })
}

Upvotes: 1

Related Questions