Sibin Francis
Sibin Francis

Reputation: 601

Laravel 5.2 How to get values from two or more table from a relationship

I have a default authentication table user and another table user_profiles

 user(id,email,password) 
 user_profiles(id,first_name,last_name,mobile)

i am connecting these two table using a many-to-many relationship for this, i added relationship in the both model class- User and UserProfile

   // User Model
 public function userProfiles()
  {
    return $this->belongsToMany('App\Models\UserProfile',  'user_user_profile', 
  'user_profile_id', 'user_id');
    }

 //UserProfile Model

 public function users()
    {
   return $this->belongsToMany('App\User', 'user_user_profile', 
  'user_profile_id', 'user_id');
  }

and i tried to access the UserProfle details via user table using

    $user=\App\User::find(1)->userProfiles()->get();

but not working and also tried

     /$user = \App\User::findOrFail(1)->with('userProfiles')->get();

that is also not working , please help to

  1. Get the user_profile table details along with user table
  2. How to access the Pivot table(user_id,user_profile_id) value
  3. How to display these data from multiple tables into a view form?

Upvotes: 0

Views: 41

Answers (1)

jaysingkar
jaysingkar

Reputation: 4435

You have defined the relationship wrong in your User Model: swap user_id and user_profile_id

// User Model
 public function userProfiles()
  {
    return $this->belongsToMany('App\Models\UserProfile',  'user_user_profile', 
   'user_id' , 'user_profile_id');
    }

Upvotes: 1

Related Questions