Skip to content
Advertisement

how to bind multiple related parameters in one route in laravel

I have Two related Models Anime, Episode

and I have changed the RouteKeyName for both of them

In Anime Model :

public function getRouteKeyName() 
{
    return 'slug';
}

In Episode Model :

public function getRouteKeyName()
{
    return 'ep_num'; // episode number
}

to view an Episode, I use this :

routes/web.php

Route::get('play/{anime}/{episode}', 'EpisodeController@index');

EpisodeController.php

public function index(Anime $anime, Episode $episode)
{
    return view('play')->with([
        'anime' => $anime,
        'episode' => $episode
    ]);
}

for example if i have this link

…/play/naruto/10

then by using route model binding i will have the first episode with ep_num=10

Instead I want to have the episode with ep_num=10 when

anime_id = $anime->id

is there any way to do this inside RouteServiceProvider

i want to apply this for all the routes containing both anime and episode such as :

Route::delete('anime/{anime}/episode/{episode}/delete', 'EpisodeController@destroy');
Route::get('anime/{anime}/episode/{episode}/edit', 'EpisodeController@edit');
Route::put('anime/{anime}/episode/{episode}/edit', 'EpisodeController@update');

Advertisement

Answer

You could do something like:

Route::bind('episode', function ($slug) {

    $episode = Episode::where('slug', $slug);

    if (request()->route()->hasParameter('anime')) {
        $episode->whereHas('anime', function ($q) {
            $q->where('slug', request()->route('anime'));
        });
    }

    return $episode->firstOrFail();
});

Hope this helps!

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement