How to get property from second relationship table using eloquent?

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.

I suspect there is some mistake on how construct the eager loading but cannot find the proper way on how to do it.

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

Thanks in advance

Answers


I don't see any error here, you before displaying any property from relationship you should make sure it really exists. For example user might have not user_info and if he has, its user_info might not to have nay branch.

So correct code for display should look like this:

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
      if ($value->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
         if ($value->user_info->branch) {
            echo $value->user_info->branch->branch_name;
         }
      }

    }
}

Need Your Help

How to select last hour without timestamp in MySQL

mysql sql datetime timestamp

I would like to select all records from the last hour. Problem is, that I don't have an timestamp. I save the time in one row, and in another the date.