Nikola
Nikola

Reputation: 53

Laravel getting data from two tables

I have a users table:

I also have a table user_status:

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.

Upvotes: 0

Views: 131

Answers (2)

Azahar Alam
Azahar Alam

Reputation: 741

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

Upvotes: 0

Narendra Choudhary
Narendra Choudhary

Reputation: 134

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;

Upvotes: 3

Related Questions