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
Please replace model.Employee
First of all you need to write your relationship properly.
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
Source here