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

realtebo's avatar

How to use count of relations where building a query?

I have this query [for datatable]

$records = Customer::select('id', 'name', 'surname', 'email', 'phone')
            ->where(function($query) use ($searchValue) {
                $query->where('name', 'like', '%' .$searchValue . '%')
                    ->orWhere('surname', 'like', '%' .$searchValue . '%')
                    ->orWhere('email', 'like', '%' .$searchValue . '%')
                    ->orWhere('phone', 'like', '%' .$searchValue . '%')
                ;
            })
            ->orderBy($columnName,$columnSortOrder)
            ->skip($start)
            ->take($rowperpage)
            ->get();

$data_arr= CustomerResource::collection($records);

Now I added to Customer class the 1 to many relation

public function orders()
    {
        return $this->hasMany(Order::class);
    }

I ask you how to get in the previous query the 'orders_count'

I tried added ::withCount('orders') but it do not append anything to returned results

To understand what is happening, I used tinker

>>> $customer = Customer::withCount('orders')->find(1);
=> App\Customer {#4129
     id: 1,
     email: "[email protected]",
     name: "Charlene 3",
     surname: "Sauer 3",
     phone: "520.390.6116 x2383-2",
     created_at: "2020-07-21 13:39:55",
     updated_at: "2020-07-22 14:27:52",
     deleted_at: null,
     orders_count: 8,
   }

This works !

But the following doesn't work anymore

>>> $customer = Customer::withCount('orders')->select('id', 'name', 'surname', 'email', 'phone')->take(1)->get();
=> Illuminate\Database\Eloquent\Collection {#3911
     all: [
       App\Customer {#4127
         id: 1,
         name: "Charlene 3",
         surname: "Sauer 3",
         email: "[email protected]",
         phone: "520.390.6116 x2383-2",
       },
     ],
   }

What's the trick ?!

Actually I worked around removing the select, but I really need it !

0 likes
2 replies
realtebo's avatar

Yes, and you? :)

It doesn't works because it caus an bovious SQL error about orders_count being not in tha table

Please or to participate in this conversation.