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

Syed1980's avatar

How can I count from two tables in my eloquent query?

I have two table named 'customers' & 'linkeds', now I want to get the count of 'customer_name'.

Below is my query.

$this->linked = $this->linked->join('customers', 'linkeds.customer_id', '=', 'customers.id')- 
>where('customer_name', $customer_name)->get();
0 likes
5 replies
Syed1980's avatar

@Sergiu17 Thanks for your reply, I already checked this docs. However, I cannot change the structure of my query, so, is there any possibilities get the count within this query structure?

Syed1980's avatar

@Tray2 Thank you, I added ->withCount('customers') to my code like this...

$this->linked = $this->linked->join('customers', 'linkeds.customer_id', '=', 'customers.id')
->where('customer_name', $customer_name)->get()->withCount('linkeds.customer_id');

I'm getting below error.

"Method Illuminate\Database\Eloquent\Collection::withCount does not exist."

I also tried giving this before ->get(), like this...

$this->linked = $this->linked->join('customers', 'linkeds.customer_id', '=', 'customers.id')
->where('customer_name', $customer_name)->withCount('linkeds.customer_id')->get();

I'm getting below error.

"Call to undefined method App\Models\Linked::linkeds()"

Am I doing it in the right way?

Syed1980's avatar

Achieved this by this line of code. Thank you very much indeed @sergiu17 & @tray2 .

$this->count = count($this->linked);

Please or to participate in this conversation.