Shahid
Shahid

Reputation: 159

How to use Multiple relationship in laravel 5.4

In my app i have define relationship (profile, user, level) but when I fetch data it is showing an error (Trying to get property 'email' of non-object) how can i solve this thank in advance.

this is User Model

public function profile()
{
     return $this->hasOne(Profile::class, 'user_id');
}

Profile Model

public function user()
{
    return $this->belongsTo(User::class, 'id');
}
public function level()
{
   return $this->belongsTo(Level::class, 'id');
}

Level Model

public function profile()
{
  return $this->hasOne(Profile::class, 'level_id');
}

This is Controller ProfileController

$users = Profile::with(['user', 'level'])->where('is_bd_partner', 'Yes')->get();
        foreach ($users as $key => $value) 
        {
            echo $value->first_name.'<br>';
            echo $value->last_name.'<br>';
            echo $value->user->email.'<br>';
            echo $value->level->level.'<br>';
        }

Upvotes: 1

Views: 68

Answers (1)

Bharat Geleda
Bharat Geleda

Reputation: 2820

Note that belongsTo takes foreign_key as the first parameter. So you should change the Profile Model as

public function user()
{
    return $this->belongsTo(User::class, 'user_id');
}
public function level()
{
   return $this->belongsTo(Level::class, 'level_id');
}

Read more here

Upvotes: 2

Related Questions