Reputation: 183
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');
Upvotes: 1
Views: 3556
Reputation: 35180
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!
Upvotes: 9