Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

integrasolid's avatar

How to get property from second relationship table using eloquent?

Hi guys,

I need help on how to get the property of relationship table using eloquent. I am building a list of users in HTML table and want to display info from three tables join together using eloquent relationship

Example:

I have 3 table users, users_profile, and branch. Each user can have one profile and one branch, and each branch can have multiple users.

users
---
id
username
email

users_profile
-----
id
user_id 
branch_id
fullname
address

branch
-----
id
branch_name

User model


public function user_info()
{
    return $this->hasOne('User_info','user_id','id');
}


User_info model

public function user() {
    return $this->belongsTo('User');
}

public function branch() {
    return $this->belongsTo('Branch');
}

Branch model


public function user_info()
{
    return $this->hasMany('User_info','branch_id','id');
}

User controller


public function index()
{
    $users = User::with('user_info')->get();
    
    foreach($users as $value)
    {
      //show data from table users
      
      echo $value->username;
      echo $value->email;
      
      //show data from table user_info
      
      echo $value->user_info->fullname;
      echo $value->user_info->address;
      
      //how to display data from table branch?
      //this code below will trigger property error
      
      echo $value->user_info->branch->branch_name;
      
    }
}

Question is how do I display data from table branch in the list as this code below will trigger Trying to get property of non-object error


echo $value->user_info->branch->branch_name;

Thanks in advance

0 likes
5 replies
michaeldyrynda's avatar

Does it always trigger an error, or only when you come across a user that doesn't have a branch attached?

// Try this
echo $value->user_info->branch ? $value->user_info->branch : null;
integrasolid's avatar

@deringer I test with 3 samples data and all data have branch id attached. I tried your code and still cannot display the branch name so I suspect the mistake is somewhere on how I query the data.

thomaskim's avatar

@integrasolid Most likely, your issues are coming up from improper namespaces. For example:

public function user_info()
{
    return $this->hasOne('User_info','user_id','id');
}

User_info should be App\User_info (or whatever namespace you put them in). In other words, it should be:

public function user_info()
{
    return $this->hasOne('App\User_info','user_id','id');
}

Or in this instance...

public function user() {
    return $this->belongsTo('User');
}

User should be App\User and so on and so forth.

michaeldyrynda's avatar

In addition, User_Info should be UserInfo.

Following the Laravel naming conventions is the path of least resistance.

Please or to participate in this conversation.