Adventures in learning Tailwind, Alpine, Laravel and Livewire
04 Oct, 2022
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