Skip to content
Advertisement

Laravel Eloquent Relationship between users table and states table with states_id in users table

I am trying to figure out relationships in laravel and have come to the end of my rope so I thought I would post my very first question here in hopes of figuring it out. I can generally find the answer here but not this time.

I have the users table like so:

  • id
  • first_name
  • last_name (etc.)
  • address_1 (etc.)
  • state_id
  • city (etc.)

Then I have a states table

  • id
  • state_abrv
  • state_name

Now from what I gather Eloquent wants the users_id stored in the states table instead of states_id stored in the users table but that does not make sense because you would have to repeat the states over and over.

On my User model I have tried

JavaScript

and

JavaScript

but I think it is looking for the foreign key on the states table and not the users table. What am I missing here?

I want to get a list of all users for example in the show user details view with their state without a second query to get all the states into an array and getting their state from that array.

Like

JavaScript

Advertisement

Answer

If I really understand what you want, you really will have to update the state method in your User Class by adding a second parameter.

JavaScript

Then you can get a user with the state relationship with

JavaScript

I added states_idas a second param because that is the column name you have provided as in your migration

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement