Skip to content

Instantly share code, notes, and snippets.



Last active Nov 25, 2020
What would you like to do?

~Laravel | Route Model Binding, bind to field other than id

When doing Route Model Binding, you can bind to another field other than id by specifying :field like slug, in case of SEO-friendly URLs.

Consider the following example.

// routes/web.php
Route::get('{category:slug}-{product:slug}', [ProductController::class, 'show']);

// ProductController
public function show(Category $category, Product $product)

Under the hood Larave will do:

$category = Category::where('slug', $categorySlug)->firstOrFail();
$product = Product::where('slug', $productSlug)->firstOrFail();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment