TALL Tales

Home About Resources Reference Posts Contact

How to Add a Sum Value to your View

18 Feb, 2021

TUTORIAL

LARAVEL

Say you have a list of posts and each post has votes attached to it and you want to summarise the total number of votes in a table.

You will have already set up a simple one-to-many relationship in both the Post model and the Vote model.

In your PostController's index function alter it to look like this:

    public function index()
    {
        $posts = Post::withSum('votes', 'amount')->get();

        return view('posts', compact('posts'));
    }

Then in the appropriate column in your table in order to show that value you will need to display:

{{$post->bills_sum_amount}}

where bills_sum_amount is model _ aggregate function _ field name.

This will of course work for other aggregate functions, please see the documentation here: https://laravel.com/docs/8.x/eloquent-relationships#other-aggregate-functions .

Photo by Clayton Robbins on Unsplash

Did this article help you? Say thanks by buying me a coffee!