Laravel - Relationships - Other Aggregate Functions

In addition to the withCount method, Eloquent provides withMin, withMax, withAvg, withSum, and withExists methods. These methods will place a {relation}_{function}_{column} attribute on your resulting models:

    use App\Models\Post;
    $posts = Post::withSum('comments', 'votes')->get();
    foreach ($posts as $post) {
        echo $post->comments_sum_votes;

If you wish to access the result of the aggregate function using another name, you may specify your own alias:

    $posts = Post::withSum('comments as total_comments', 'votes')->get();
    foreach ($posts as $post) {
        echo $post->total_comments;

Like the loadCount method, deferred versions of these methods are also available. These additional aggregate operations may be performed on Eloquent models that have already been retrieved:

    $post = Post::first();
    $post->loadSum('comments', 'votes');

If you're combining these aggregate methods with a select statement, ensure that you call the aggregate methods after the select method:

    $posts = Post::select(['title', 'body'])