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

CH17's avatar
Level 3

Eloquent way to design a table

Hello All, I have a courses table, lessons table, quizes table and a chapters table. A course may have many chapters. A chapter may have one or more quizes and one or many lessons. At the end I've to query a course with chapters and for each chapters its items (Lessons and Quizes). I've done it with Raw Query but I think there might be better eloquent way to do it. I was trying polymorphic relationship but still couldn't find the best approach.

Please guide me to a better way. I'd really appreciate any suggestion.

Thanks

0 likes
1 reply
gitwithravish's avatar

Table Structure

chapters
    id
    name


chapter_items
	id
	course_id
	itemable_id
	intemable_model


lectures
    id
    name


quizes
	id
	name

Models

class Course extends Model
{
    public function chapters()
    {
        return $this->hasMany('App\Model\Chapter');
    }
}


class Chapter extends Model
{
    public function items()
    {
        return $this->hasMany('App\Model\Chapter');
    }
}


class ChapterItem extends Model
{
    public function itemable()
    {
        return $this->morphTo();
    }
}

class Quizes extends Model
{
    public function comments()
    {
        return $this->morphMany('App\Models\ChapterItem', 'itemable');
    }
}

class Video extends Model
{
    public function comments()
    {
        return $this->morphMany('App\Models\ChapterItem', 'itemable');
    }
}

Retrive items

Course::find($id)->with('chapters.items.itemable')->first()

Docs https://laravel.com/docs/5.4/eloquent-relationships#polymorphic-relations

Please or to participate in this conversation.