skip to Main Content

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(Department::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 class="text-center">{{ $item->employee_name}}</td>
  <td class="text-center">{{ $item->department->department_name}}</td>
  <td class="text-center">{{ $item->email}}</td>
  <td class="text-center">{{ $item->telephone}}</td>
</tr>
@endforelse

But then it said

Attempt to read property "department_name" on null

What do I do wrong.

2

Answers


  1. Please replace model.Employee

    public function department()
    {
        return $this->belongsTo(Department::class, 'id_department');
    }
    
    Login or Signup to reply.
  2. 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

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search