Home > Software engineering >  Laravel getting data from two tables
Laravel getting data from two tables

Time:04-08

I have a users table:

  • ID
  • username
  • user_status <- which can be 0 or 1, depending if the user is active or not.

I also have a table user_status:

  • user_status_id
  • user_status_description

How can I get data from user_status_description in an elegant way? I can get the user_status with {{Auth::user()->user_status}} or via UsersController ($user_status = auth()->user()->user_status;), but I can get a hold on how to join with another table, so I could do something like Auth::user()->user_status_description or something like that.

CodePudding user response:

You can achieve by Belongsto relationship. Put below relation in User eloquent

public function statusDescription() {
   return $this->belongsTo('App\UserStatus', 'user_status', 'user_status_id');
}

To get user user_status_description as bellows.

Auth::user()->statusDescription->user_status_description;

CodePudding user response:

My solution is a bit intimidating.

  1. Create a migration file so that you can add a column to users table.

  2. In the migration file create a column named 'user_status_description'

  3. Copy all the data from user_status table user_status_description to users

table user_status_description column.By using user_id.

4.Drop the user status table.

Then you can easily do Auth::user()->user_status_description

  • Related