Below is an example that handles both cases—when the slug is missing (only the ID is present) or when the slug in the URL does not match the article's current slug. In either case, the user is redirected to the canonical URL with the proper ID and slug.
1. Update the Article Model
Make sure your model generates a slug (using spatie/laravel-sluggable for example) and override the getRouteKey() method so that the URL generation automatically uses the "id-slug" format:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;
class Article extends Model
{
use HasSlug;
protected $fillable = ['title', 'content', 'slug'];
public function getSlugOptions(): SlugOptions
{
return SlugOptions::create()
->generateSlugsFrom('title')
->saveSlugsTo('slug');
}
// This method is used by the route() helper to generate the proper URL.
public function getRouteKey()
{
return "{$this->id}-{$this->slug}";
}
}
2. Define the Route
Allow an optional slug in the URL. By making the slug portion optional (using a non-capturing group with (?:...) and a ?), the route will match URLs like /articles/122 as well as /articles/122-my-article-title:
<?php
use App\Http\Controllers\ArticleController;
use Illuminate\Support\Facades\Route;
Route::get('/articles/{article}', [ArticleController::class, 'show'])
->name('articles.show')
->where('article', '[0-9]+(?:-[a-z0-9-]+)?');
3. Update the Article Controller
In the controller, parse the incoming route parameter to extract the ID and slug parts. Then load the article by its ID. If the slug found in the URL is missing or does not match the article’s current slug, redirect to the canonical URL using the helper route("articles.show", $article):
<?php
namespace App\Http\Controllers;
use App\Models\Article;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
public function show($article)
{
// Determine the position of the first hyphen to separate the ID from the slug.
$pos = strpos($article, '-');
if ($pos !== false) {
$id = substr($article, 0, $pos);
$slug = substr($article, $pos + 1);
} else {
// Only ID was provided.
$id = $article;
$slug = null;
}
// Fetch the article using the ID.
$articleModel = Article::find($id);
if (!$articleModel) {
abort(404);
}
// If the slug is missing or doesn't match, redirect to the canonical URL.
if ($slug !== $articleModel->slug) {
return redirect()->route('articles.show', $articleModel);
}
return view('articles.show', compact('articleModel'));
}
}
4. Generate the URL in a Blade Template
With the getRouteKey() override in your model, you can generate the URL using the route() helper, and it will automatically create the id-slug URL:
<a href="{{ route('articles.show', $article) }}">{{ $article->title }}</a>
How It Works
-
Routing:
The route defined in routes/web.php uses a regular expression to accept either just an ID or an ID followed by a hyphen and a slug.
-
Controller:
The controller extracts the numeric ID and slug (if present) from the route parameter. It then loads the Article and checks whether the URL slug matches the stored slug. If the slug is missing or incorrect, it uses redirect()->route() to send the user to the correct URL.
-
URL Generation:
The getRouteKey() method in the Article model ensures that when you generate a route (using route('articles.show', $article)), you get the proper id-slug URL.
This way, you ensure that your application always shows the canonical URL (e.g., /articles/122-my-article-title) even if the user types only the ID or an outdated slug.