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

syerkes's avatar

Split Model Into Multiple Corresponding Tables

Hi!

I'm hoping someone can help. I'm interested in designing my app against Laravel norm (maybe even best practice), perhaps there is something out there I don't know about to achieve this design.

I'd like to use eloquent and standard model relations as much as possible, but I'd like to split a model so it saves and reads from dynamic prefixed tables based on the model's parent relationship.

For instance - two models, Courses (metadata about the course) and Class (list of students in each class). I'm envisioning the Class model will actually save to tables in the database like class_math_101, class_hist_102, etc.

I realize I could achieve the same result in a classic one to many relationship with courses.id => classes.course_id, but for my app's reporting requirement I'm wondering if splitting it up into different tables (similar to a WordPress multisite database structure) might be beneficial.

I know you can overwrite the model's table property but I'm not sure how to do so dynamically. Any clues would be appreciated! Thanks.

0 likes
3 replies
Snapey's avatar
Snapey
Best Answer
Level 122

unless you are faced with problems of table size (millions of rows) and need to partition the data, then I would probably stick with one table and look into scopes so that you can get results filtered by class

You might find some discussions on multi-tenancy useful with respect to shared or discrete tables / databases

Tray2's avatar

The idea of class_math_101, class_hist_102 makes my skin crawl. It add complexity to you application that you don't need and it also forces you to write more unions between tables and lots of custom SQL. The worst part is that you need replicate database functionality and the likelyhood of you writing more efficient code than the database already has is slim to none.

You need a courses table, a classes table and a pivot table joining those together. Then you need a paticipants/students table and a pivot table linking the students to courses and to classes.

Please or to participate in this conversation.