In this episode, we're diving deeper into aggregate functions, specifically focusing on how to sum up columns in your database using Laravel. Previously, we looked at the count
aggregate, but now we're exploring other useful aggregates like sum
, min
, and max
. The star of the show for most apps is probably going to be sum
, so that's what we zero in on.
We walk through a fictional scenario where articles (or comments) get votes. To enable summing votes, we start by editing the articles table: we run a migration to add a votes
column and set it up with a default value. Then, we seed some data into the articles to play around with.
You’ll see how to perform the sum directly with a database query (instead of summing things up in a PHP collection), keeping things efficient. We use Laravel's query builder methods to sum up the votes for articles in just a single database call. The episode shows step-by-step how to update your code, run the migrations, and even display the result in your view.
Plus, there’s a quick tip on how you can alias the resulting sum in your queries, so it's named however makes the most sense for your project.
By the end of the video, you'll be good to go with summing up columns using Laravel—whether it's for votes, sales, points, or anything else that needs totaling!