Search code examples
laraveleloquent-relationship

Get data from three models with relationship laravel


I have three models :

Serie ($id)

public function saisons() 
{
    return $this->hasMany(Season::class);
}

public function episodes() 
{
    return $this->hasManyThrough(Episode::class, Season::class);
}

Season ($serie_id)

public function serie()
{
    return $this->belongsTo(Serie::class);
}

public function episodes() 
{
    return $this->hasMany(Episode::class);
}

Episode ($season_id)

public function season()
{
    return $this->belongsTo(Season::class);
}

public function serie()
{
    return $this->BelongsToThrough(Serie::class, Season::class);
}

I would like to show one specific season from a serie with the episodes associated

My view

<h1 class="title">{{$serie->seasons->number}}</h1>


@foreach ($serie->seasons->episodes as $episode)

        <div class="row">
            <div class="columns">
                <div class="col">
       {{$episode->number}}
       <a href="{{route('episodes.show', $episode->id)}}">{{$episode->name}}</a>



        @if(isset($episode->programmation->date))

            {{$episode->programmation->date}}

        @endif
       @if (($episode->season_finale) == '0')
            Non
            @elseif (($episode->season_finale) == '1')
            Oui
            @endif

        @foreach ($episode->chaines as $chaine)
                   {{$chaine->name}}

            @endforeach
        </div>
        </div>
    </div>
    @endforeach

Route

Route::get('/serie/{serie}/saison/{season}', 'Front\SaisonController@show')->name('saison.show');

For my url, I choose to show the number of the saison and not the id and I think that's the problem.

How can I do that in a proper way ?


Solution

  • Ok, someone help me to find the right answer :

         $serie = Serie::findOrFail($serie);
         $season =  Season::where('serie_id', $serie->id)->where('season.number', $season)->first();