Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

joshblevins's avatar

Get count on relationship for each row

I have three tables with working relationships set up in the model's.

  1. narcotic_wastes (holds forms for each time an employees wastes a form)

  2. controlled_substances (Holds medication data of each medication vial on hand) joined to narcotic_wastes by vial_id.

  3. 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.

0 likes
2 replies
joshblevins's avatar

So now I have tried

$nw = NarcoticWaste::with(['vial' => function($query)
        {
            $query->select('medication', DB::raw('count(*) as use_count'));
            $query->groupBy('medication');
        }])
        ->withCount(['vial'])
            ->get();
            
       foreach($nw as $nw)
       {
        $nw->vial_count;
       }

on view

@foreach($nw as $nw)

{{$nw}},
@endforeach

The response is 1 1 1

Which I would assume should have been 1, 1 since I added another record for a different medication.

When I try $nw->vial _count I get an error Trying to get property 'vial_count' of non-object

Please or to participate in this conversation.