Support the ongoing development of Laravel.io →
Database Eloquent Installation
Last updated 2 years ago.
0

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.

Last updated 8 years ago.
0

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
Last updated 8 years ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

njuarezgt njuarezgt Joined 2 Oct 2015

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.