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

lirone's avatar

Get user's record via model ?

I'm starting learning Laravel and I wonder about the way to retrieve some data. I have 4 tables

  • Users
  • Records
  • RecordsA
  • RecordsB

An Users may have multiple records. (Records has a foreign key of user) RecordsA has a foreign key of Records RecordsB has a foreign key of Records

I would like to retrieve records (A or B) from an User and I wonder what is the best way to do it.

  1. Write functions to the user's repository getRecordA() and getRecordB() so that I could do in my controller, $this->user->getRecordA() and user->getRecordB()

  2. Write functions to recordA's repository and recordB's repository ? So I will inject the id of the user in the query. So in my controller, I could write recordA->get(User $user)

I'm asking that, because the user is the core of my app and I have many tables (among Records, RecordsA and RecordB) that are linked to my user and I'm affraid that my user table will be huge. However, for me it's intuitive to put all the related function to the user repository.

What do you think ? Could you please give the good practice ?

0 likes
3 replies
jlrdw's avatar

I had something similar, I had

                loads
  picks                  drops

picks and drops were both child to loads. You just basically have two one to many relations.

I wouldn't look and it like A or B. You probably need to do something like:

Records
---- RecordsA data 
---- RecordsB data

I don't know your total setup, but in my example was:

loads i.e. load 1245784
---- list of pickups for truck
---- list of deliveries for truck

Of course a little more complex than that, you could have 2 picks, a drop, another pick, 2 drops, so you had to "build the load" accordingly.

lirone's avatar

Thank for your answer ! What do you suggest for methods ? Put everything in my user repo or each method its according repo (RecordA and RecordB) ?

jlrdw's avatar

Not knowing how A and B relate or what data they hold makes it hard to know.

Maybe you could do a has many through https://laravel.com/docs/7.x/eloquent-relationships#has-many-through

Another example I can point to is income and expense reporting. Yes you could have two tables, but one makes more sense. It boils down to is this an expense or income. See this post:

https://laracasts.com/discuss/channels/general-discussion/rental-management-db-schema

So ask yourself do you need A and B or just one table with a flag to denote a difference.

A flag meaning in my example expense or income.

Just a simplified example there, because there are related tables with expense or income accounts.

And sorry I use business type examples, but that's all I do is business type programming.

Please or to participate in this conversation.