Recommand · May 25, 2021 0

Route model binding with multiple wildcards

How to explicitly say to route model binding to fetch only related categories? I have my web.php file as follows:

Route::get('/catalog/{category}', [CategoryController::class, 'index'])->name('category.index');
Route::get('/catalog/{category}/{subcategory}', [SubcategoryController::class, 'index'])->name('subcategory.index');
Route::get('/catalog/{category}/{subcategory}/{subsubcategory}', [SubsubcategoryController::class, 'index'])->name('subsubcategory.index');

Subsubcategory controller:

public function index(Category $category, Subcategory $subcategory, Subsubcategory $subsubcategory)
{
    $subsubcategory->load('product')->loadCount('product');
    $products = Product::where('subsubcategory_id', $subsubcategory->id)->orderByRaw('product_order = 0, product_order')->get();
 return view('subsubcategory.index', compact('subsubcategory', 'products'));
}

And model in question:

public function subcategory()
{
    return $this->belongsTo(Subcategory::class);
}

public function category()
{
    return $this->belongsTo(Category::class);
}

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

It works partially ok. It loads all the slugs, but the problem is, let’s say I have Samsung Subsubcategory with it’s parent categories like:

catalog/mobile-phones/android/samsung

Whenever I modify url from catalog/mobile-phones/android/samsung to catalog/mobile-phones/ios/samsung it works, where in fact it should not. How to handle this second scenario?

PS: it also applies if I open subcategory and change category slug. But, obviously, if upper level category does not exists, it’s going to throw 404.