I'm the beginner of laravel 5.4. I just want to ask. I want to display in Assignments table the Collectors but it doesn't show.
Screenshot of the Assignments Index
Code in my Assignment index.blade.php
<td>{{ $assignment->collector['firstname'] }} {{ $assignment->collector['lastname'] }}</td>
Assignment.php model
public function collectors()
{
return $this->belongsToMany(Collector::class);
}
Collector.php model
public function assignments()
{
return $this->belongsToMany(Assignment::class);
}
AssignmentsController
public function index()
{
$assignments = Assignment::all();
return view('assignments.index', compact('assignments'));
}
I search to how to display the collectors with both many to many relationship. I read the doc about using pivot but I had still errors about that. Can you help me resolving this? Thanks
$collector
is an object, not an array. Use ->
syntax to access properties on individual collector models:
$collector->firstname
Since the relationship is many to many you need two loops:
@foreach($assignments as $assignment)
@foreach($assignment->collectors as $collector)
<td>{{ $collector->firstname }} {{ $collector->lastname }}</td>
@endforeach
@endforeach
If you find you often need two fields together, like first and last names, you can create an accessor on the Collector
model to easily join them:
public function getFullNameAttribute()
{
return $this->getAttribute('firstname') . ' ' . $this->getAttribute('lastname');
}
Allowing you to then do:
@foreach($assignments as $assignment)
@foreach($assignment->collectors as $collector)
<td>{{ $collector->fullname }}</td>
@endforeach
@endforeach