That is weird code. If you are creating the employee, why are you then finding that same employee? Also, you should be attaching the department id, not the employee id.
Yes Thomastkim you have reason, thanks for the logic! :D I'm no sleep good for a very days for this, now do you can help me to a get eager loading pls?
Save new Employee and attach department to pivot:
public function store(Request $request)
{
$employee=Employee::create([
'name' => $request->get('name'),
'lastname' => $request->get('lastname'),
'job' => $request->get('job'),
]);
//$employee=Employee::find($employee->id);
$employee->departments()->attach($request->department_id);
Employee model with select a column:
public function departments()
{
$query= $this->belongsToMany('Tlc\Department')
->select(['name_department']);
return $query;
}
Employee Controller:
public function index()
{
$employees= Employee::with('departments')->get();
return view('employee.index', compact('employees'));
}
Employee View
@foreach($employees as $employee)
<tbody>
<td>{{$employee->id}}</td>
<td>{{$employee->name}}</td>
<td>{{$employee->lastname}}</td>
<td>{{$employee->job}}<td>
<td>{{$employee->departments}}</td>
@endforeach
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community