HasH
HasH

Reputation: 949

Managing routes for multiple models using slugs without prefixes in Laravel

I'm trying to implement a routing structure in Laravel where multiple models (e.g., Article, Product, and Category) share the same slug-based URLs without prefixes (e.g., example.com/slug). However, I'm facing an issue where it's difficult to distinguish between the models when resolving the slug.

Here is the code I've written so far:

// RouteServiceProvider.php

Route::bind('slug', function ($slug) {
$article = Article::where('slug', $slug)->first();
if ($article) {
    return ['type' => 'article', 'data' => $article];
}

$product = Product::where('slug', $slug)->first();
if ($product) {
    return ['type' => 'product', 'data' => $product];
}

abort(404);
});

When two slugs from different models conflict (e.g., an article and a product have the same slug), the system fails to resolve them correctly. I want to ensure that the routing structure is efficient and avoids unnecessary database queries.

Upvotes: 0

Views: 44

Answers (0)

Related Questions