How to get get data via 3 tables connected pivot in php laravel

  laravel, laravel-7, php, pivot, pivot-table

I faced an issue where I’m unable to retrieve data through the pivot table,

In my application there’s a separate table to store the files data and a separate table to store the competition and a separate table to store the teams.

And there’s a table named competition_file which has the competition_id, team_id, file_id.

enter image description here

a user can add multiple files to a competition by selecting a team or by not selecting a team as show in the below image

enter image description here

It will be synced to the competition_file table as shown in the below image

enter image description here

I need to show all data in the UI as a table shown in below image

enter image description here

I’m wondering how can I fill the team name selected using the pivot table

Here’s the relationship’s i have used in my competition Model

 public function team()
{
    return $this->belongsToMany(Team::class, 'competition_file')->wherePivot('type','document');
}

public function documents()
{
    return $this->belongsToMany(File::class,'competition_file')->wherePivot('type','document');
}

And this is my controller index function

 public function index($id)
    {
        $competition = $this->competitionsRepo->find($id,[
            'team',
            'documents',
        ]);

        return view('competitions.document',[
          
            'competition'=>$competition,
        ]);
    }

My Blade

    @foreach ($competition->documents as $key=>$document)
                                <tr>
                                    <td>{{ $key+1 }}</td>
                                    <td>{{ $document->name }}</td>
                                    <td>-</td>
                                    <td>{{ $document->created_at->toDateString() }}</td>
                                    <td>
                                        <form class="confirm" action="{{ route('documents.destroy',['competition'=>$competition,'document'=> $document->id]) }}" method="POST"
                                            data-confirm-title="Remove Document?"
                                            data-confirm-message="Are you sure you want to remove this document?">
                                            @csrf
                                            @method('DELETE')

                                            <button type="submit" name="button" class="button">Remove</button>
                                        </form>
                                    </td>
                                </tr>
   @endforeach

Someone please help me out to get the team names to my foreach in the blade

Source: Laravel

Leave a Reply