How to use withSum() with where condition

You can use withSum in query with where condition, here is an example:

If you want to list all Projects with the sum of all invoices that were issued this year:

$projects = Project::select('id', 'name', 'created_at')
            ->withSum(
                 ['invoices as prev_invoices' => function($query) {
                     $query->whereYear('invoices.issue_date', date('Y'));
                }], 'amount' 
             )
            ->get();

Leave a Reply

Your email address will not be published. Required fields are marked *