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

ziayamin's avatar

How to get data from three related table with it's model relationships?

I have three tables like these:

Expense:-

expense_id
user_id

User:-

user_id
employee_id

Employee:-

employee_id
first_name
last_name

I want to get first_name and last_name from the employee table where expense.user_id = user.user_id, I tried something like bellow, but I did not get the correct data.

Expense model:-

public function users(){

return $this->hasMany(User::class,'user_id','user_id');

}

User model:-

public function employee(){
     return $this->hasOne(Employee::class,'employee_id','user_id');
}

And employee model:-

public function users()
{
     return $this->belongsTo(User::class,'employee_id');
 }

I called to view like this:-

 <td>{{$expense->users->employee->first_name ." " . $expense->users->employee->last_name }}</td>

It shows data, but not as expected data.

Where is my mistake and how it should be? please help! thanks!

0 likes
4 replies
ziayamin's avatar

@corvs you are right, a user can have much expense, It is my mistake that not edited my code, I tried that way too, both are the same.

CorvS's avatar

@ziayamin Your relationships are still wrong. A user has multiple expenses and an expense belongs to one user.

// User.php
public function expenses()
{
    return $this->hasMany(Expense::class);
}

// Expense.php
public function user()
{
    return $this->belongsTo(User::class);
}

Additionally you probably want to add a user_id column to your employees table. Since a user has one employee and an employee belongs to a user. It seems like you didn't understand how relationships are defined. Go check out the docs and try applying it to your case.

1 like

Please or to participate in this conversation.