try using withCount(relationship) in addition to with(relationship)
https://laravel.com/docs/5.7/eloquent-relationships#counting-related-models
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
I have three tables with working relationships set up in the model's.
narcotic_wastes (holds forms for each time an employees wastes a form)
controlled_substances (Holds medication data of each medication vial on hand) joined to narcotic_wastes by vial_id.
medications (Holds medication names) joined to constrolled_substances by id
I am trying to query a count for each medication used each month for the last 12 months.
I have started to build the query but have got stuck at grouping by each medication.
$nw = NarcoticWaste::with(['vial' => function($query)
{
$query->select('medication', DB::raw('count(*) as use_count'));
$query->groupBy('medication');
}])
->get();
if($nw->vial->isEmpty()){
}else{
foreach ($nw as $nw)
{
$nw->medication->count();
}
}
I get an error showing collection 'vial' does not exist.
When I run this query;
select `medication`, count(*) as use_count from `controlled_substances` where `controlled_substances`.`id` in ('259') group by `medication`
I get a response of medication 1 and use_count 1. This is the correct response as for their is only one record.
try using withCount(relationship) in addition to with(relationship)
https://laravel.com/docs/5.7/eloquent-relationships#counting-related-models
Please or to participate in this conversation.