Home > other >  Laravel get value from another table based on id
Laravel get value from another table based on id

Time:09-28

I want to get department_name from department table with

table department = id, department_name, total_employee
table employee = id, employee_name, id_department, email, telephone, gender, status

I tried model.Employee

public function department()
{
    return $this->belongsTo(Departemen::class);
}

controllers.EmployeeControllers

public function index()
    {
        $data_employee = Employee::with('department')->get();
        return view ('employee.index', compact('data_employee '));
    }

with view

@forelse ($data_employee as $item)
<tr>
  <td >{{ $item->employee_name}}</td>
  <td >{{ $item->department->department_name}}</td>
  <td >{{ $item->email}}</td>
  <td >{{ $item->telephone}}</td>
</tr>
@endforelse

But then it said

Attempt to read property "department_name" on null

What do I do wrong.

CodePudding user response:

First of all you need to write your relationship properly.

public function department()
{
    // You have to provide correct model name here.
    return $this->belongsTo(Department::class); 
}

Secondly Eloquent determines the foreign key name by examining the name of the relationship method and suffixing the method name with _id. So, in your case, Eloquent assumes that the Employee model has a department_id column. But, the foreign key on the Phone model is not department_id , you may pass a custom key name as the second argument to the belongsTo method

public function department()
{
    return $this->belongsTo(Department::class, 'id_department');
}

Source here

CodePudding user response:

Please replace model.Employee

public function department()
{
    return $this->belongsTo(Department::class, 'id_department');
}
  • Related