You could do
Clientes::with('clientes_contactos')
->addSelect(DB::raw('count(*) as total'))
->groupBy('clienteid')
->get();
I've not tested but should work (you might need to tinker a bit).
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Eloquent, Query Builder or other way?
Hi to all! I want to present a tablet with clients and the “number” of related records, in this case number of orders from CONTACTS table. In php I had can resolve this in two ways!
FIRST WAY Make a simple join select with count like this: SELECT clientes.*, Count(clientes_contactos.cliente_id) AS ncontactos FROM clientes LEFT JOIN clientes_contactos ON clientes_contactos.cliente_id = clientes.clienteid GROUP BY clientes.clienteid
SECOND WAY include a php with the query inside just getting the records for that $id.
In Laravel I can transform the eloquent to “count” trough query builder that and the result from FRIST option, don’t’ have the smallest idea how to get the result from second way (above) in Laravel.
Right now getting results with: $dados = clientes::all(); return view('clientes.listar', compact('dados'));
In image below present the count number in place of the RED circle. https://1drv.ms/u/s!Amqa9MXG8tF5mIoHo9BULDIWJB0dyQ
What would be the best approach for this case and similar? Thanks in Advance! Amaro
It will tremendously simplify your life, and code.
I'd highly recommend watching
Please or to participate in this conversation.