To implement ID+slug routes for an Article model in Laravel 12, follow these steps:
- Install the
spatie/laravel-sluggable package to handle slug generation:
composer require spatie/laravel-sluggable
- Update the
Article model to use the HasSlug trait and define slug options:
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class Article extends Model
{
use HasSlug;
public function getSlugOptions(): SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('title')
->saveSlugsTo('slug');
}
public function getRouteKey()
{
return "{$this->id}-{$this->slug}";
}
}
- Define the route in
routes/web.php to capture the ID and slug:
Route::get('/articles/{article}', [ArticleController::class, 'show'])
->name('articles.show')
->where('article', '[0-9]+-[a-z0-9-]+');
- Create the
ArticleController to handle the route logic:
use App\Models\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
public function show($article)
{
$parts = explode('-', $article, 2);
$id = $parts[0];
$slug = $parts[1] ?? '';
$articleModel = Article::find($id);
if (!$articleModel) {
abort(404);
}
if ($articleModel->slug !== $slug) {
return redirect()->to("/articles/{$articleModel->id}-{$articleModel->slug}", 301);
}
return view('articles.show', compact('articleModel'));
}
}
- Use the
route() helper in a Blade template to generate the URL with the ID and slug:
<a href="{{ route('articles.show', $article) }}">{{ $article->title }}</a>
This implementation ensures that articles can be accessed via URLs like /articles/122-my-article-title, and it handles cases where the slug doesn't match by redirecting to the correct URL. The spatie/laravel-sluggable package simplifies slug generation and management, and the getRouteKey() method ensures that the route() helper generates the correct URL format.