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

public function state()
{
    return $this->belongsTo(State::class);
}

and

public function state()
{
    return $this->hasOne(State::class);
}

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

$users = User::with('state')->get();

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.

public function state()
{
    return $this->belongsTo(State::class, 'states_id'); // if the column name in your users migration is state_id then you might not need the second param. 
}

Then you can get a user with the state relationship with

$users = User::with('state')->get();

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