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;
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
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
Please or to participate in this conversation.