How to get the SUM of a column in a relational database "Laravel5" I hope somebody could help me with my problem. I’m stack with this little relational issue with Laravel 5.
Problem:
I want to get the SUM of my "amount" column in may "Wallet" model.
My current code that is working.
public function children()
{
    return  $this->hasMany('App\Tree', 'parent_id','id')
->with('children')
->with('user')
->with('user.wallets');
}

Note: This return with the following data.
[{
    ...,
    children: [...]
    user: {
...,
wallets: [...] // return list of array
    }
}]

My solution but return no luck.
return  $this->hasMany('App\Tree', 'parent_id','id')
->with('children')
->with('user')
->with('user.wallets', function($q) {
$q->sum('amount');
});

desired result
[{
    ...,
    children: [...]
    user: {
...,
wallets: [
...,
amount: XXX.XX // e.g The total sum of the column, could be any number based on the sum of the column.
]
    }
}]


You can use a modified withCount(). Change your user and children relationships:
public function user()
{
    return $this->belongsTo('App\User')
->withCount(['wallets as wallets_amount' => function($query) {
$query->select(DB::raw('sum(amount)'));
}]);
}

public function children()
{
    return $this->hasMany('App\Tree', 'parent_id', 'id')
->with('children', 'user');
}

Then you can access the sum with $user->wallets_amount: