I want to use many-to-many relationship for the first time, initially I had four one-to-many relationships and all the information was displayed in index form. Then I decided to write the table of offices in many-to-many with tasks table, so I changed the codes as follows:
in task model:
public function Office(): BelongsToMany
{
// return $this->belongsTo(Office::class, 'office_id');
return $this->belongsToMany(Office::class);
}
in office model :
public function tasks(): BelongsToMany
{
// return $this->hasMany(Task::class,'office_id');
return $this->belongsToMany(Task::class);
}
in controller with three one-to-many and one many-to-many relations:
public function index()
{
$tasks = Task::where('type', 0)
->with(['Office', 'Commander', 'Status', 'Priority'])
->Sortable()
->paginate(8);
return view('taskmanager.tasks.index',compact('tasks'));
}
and in index form (view):
@foreach($tasks as $item)
<tr>
<td>{{$item->id}}</td>
<td>{{$item->Caption}}</td>
<td>{{$item->Commander->Desc}}</td>
<td>{{$item->Priority->Desc}}</td>
<td>{{$item->Status->Desc}}</td>
<td>{{$item->office->caption}}</td> //line with error
<td>
</tr>
@endforeach
but in line {{$item->office->caption}}
I get an error :Property does not exist on this collection instance.
As I said before, I don’t have this error in one-to-many mode, how can I edit and run it?