Hello Steve,
It seems like you're encountering an issue with Eloquent trying to hydrate models with only a subset of the necessary attributes. When you're using groupBy and selecting specific columns, Eloquent expects that the primary key (id in this case) is also selected, or else it will throw an error when trying to create models from the result set.
To solve this, you can either include the id in the select statement or, if you don't need Eloquent models and just want an array of results, you can use the get() method with the ->toArray() to avoid model hydration.
Here's how you can adjust your query:
$invoices_by_source = Invoice::query()
->select(DB::raw('count(*) as invoice_count, invoice_sources.short'))
->join('invoice_sources', 'invoices.invoice_source_id', '=', 'invoice_sources.id')
->where('date', '>=', $date_start)
->where('date', '<=', $date_end)
->groupBy('invoices.invoice_source_id', 'invoice_sources.short')
->orderBy('invoice_sources.short')
->get()
->toArray(); // Convert the collection to an array
return dd($invoices_by_source);
Note that I've added invoice_sources.short to the groupBy clause because you're ordering by it, and SQL standards require that all selected columns in an aggregate query that are not aggregated should be included in the GROUP BY clause.
If you do need the id for some reason, you can include it in the select statement, but be aware that it won't make sense to have it there since you're grouping by invoice_source_id and thus there will be multiple id values for each group:
$invoices_by_source = Invoice::query()
->select(DB::raw('count(*) as invoice_count, invoice_sources.short, invoices.invoice_source_id'))
->join('invoice_sources', 'invoices.invoice_source_id', '=', 'invoice_sources.id')
->where('date', '>=', $date_start)
->where('date', '<=', $date_end)
->groupBy('invoices.invoice_source_id', 'invoice_sources.short')
->orderBy('invoice_sources.short')
->get();
return dd($invoices_by_source);
In this case, the id column will be included, but it will be the id of the last invoice in each group, which may not be meaningful.
I hope this helps you resolve the issue. Let me know if you have any further questions.
Best regards, LaracastsGPT