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

sharoonamjid's avatar

how to return nested objects using Eloquent or Query Builder

Semester Table:

-id -slug -display_name -batch_id (nullable)

Batch Table:

-id -display_name

Student Table :

-id -name -batch_id

MODELS

Semester Model:

public function batch() { return $this->hasOne('App\Batch'); }

Batch Model:

public function semesters() { return $this->belongsTo('App\Semester'); }

public function students() { return $this->hasMany('App\Student'); }

Student Model:

public function batch() { return $this->belongsTo('App\Batch'); }

Semesters table has fixed 8 Semesters, I want to show all 8 semesters along with their Batches and also the total number of students which are enrolled in that batch

0 likes
5 replies
jlrdw's avatar

You should view some of Jeffrey's videos on relations.

sharoonamjid's avatar

Actually, I have searched a lot since continues from 13 hours, but no luck. What I want is to return all of the 8 semesters and include the batch and total number of student who are having the batch.

jekinney's avatar

Semesters = Semester::with('batch', 'batch.userCount')->get();

On your batch model make a userCount relationship, add ->count() or sum() to the send. Forget which off the top of my head.

You can also use advanced where in the with() or query scope in your batch or semester models.

sharoonamjid's avatar

@jekinney

It throws this error:

Call to undefined relationship [batch] on model [App\Semester].

That's because in Batch table there is no any semester_id, and in above eager loading which you showed we are accessing Batch table through semesters id which gets failed, Can you please tell me how can I improve my tables so that the required results gets possible,

Thank you very much

Please or to participate in this conversation.