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

aGreenCoder's avatar

Count data using Laravel eloquent query from multiple table

I have 3 table 'Admins', 'Agent', 'Books'

Admin can add multiple Agents, Agents can add multiple books.

Now I need to count the book for a single Admin. (Every table has the proper foreign key).

How can I achieve this?

My code

//In Controller
$data = Admin::latest()->withCount('count')->get();

//In Admin.php
public function count(){
  return $this->hasMany(Agent::class, 'adminId', 'id');
}

//In Agents.php
public function count(){
  return $this->hasMany(Books::class, 'AgentId', '???');
}

//In Book.php
public function count(){
  return $this->belongsTo(???::class, ???);
}

??? - I don't know which Id or class need to pass.

Can anyone help to solve this issue, please?

0 likes
2 replies
sr57's avatar
sr57
Best Answer
Level 39

st like this



DB::table("books r1")
->join("agents r2", function($join){
	$join->on("r1.agent_id", "=", "r2.id");
})
->join("admins r3", function($join){
	$join->on("r2.admin_id", "=", "r3.id");
})
->select("count (*)")
->where("r3.id", "=", $my_admin_id)
->get();

Please or to participate in this conversation.