I'm trying to get the data linked to my model out of the pivot table (many to many relationship).
I put customers on a many to many relationship with departments.
The migration:
Schema::create('customer_department', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('customer_id');
$table->unsignedBigInteger('department_id');
$table->timestamps();
$table->foreign('customer_id')
->references('id')
->on('customers');
$table->foreign('department_id')
->references('id')
->on('departments');
});
The customer model:
public function department(){
return $this->belongsToMany('App\Department');
}
The department model:
public function customer(){
return $this->belongsToMany('App\Customer');
}
Now I'm trying to print out every department the customer is assigned to in the view. I tried
{{$customer->department}}
or
@foreach($customer->department as $depo)
{{$depo->name}}
@endforeach
or
{{$customer->pivot->department_id}}
...
the controller:
public function show(Customer $customer)
{
return view('/customers/customer', ['customer' => $customer]);
}
However, I get several error messages, empty arrays, or straightup nothing. What am I doing wrong? What did I forget?
You have to have the model retrieved via the Many to Many relationship for it to have this attached pivot
model. $customer
would not have this pivot
but everything returned from $customer->department
would have these pivot
models attached:
@foreach ($customer->department as $department)
{{ $department->pivot->department_id }}
@endforeach
Though, in this case you don't need to involve the pivot model since you want information from the Department models:
@foreach ($customer->department as $department)
{{ $department->getKey() }}
{{ $department->name }}
@endforeach
It would be a good idea to name these relationships in the plural since they return many, not in the singular.