Laravel community member Aaron Francis shared an awesome video demonstrating how to Make self-healing URLs with Laravel. Without surprise, multiple packages in the Laravel ecosystem have already surfaced:
- Luke Downing's package: self-healing-urls
- Chris Page's package: laravel-self-healing-urls
These packages have a similar goal: you can change your model's route slug at will or only partially match a URL and never have to worry about SEO indexing when the slug changes. Both packages work by adding a trait to a model (this example is taken from Luke's package), which handles identifying the model via route model binding:
use Lukeraymonddowning\SelfHealingUrls\Concerns\HasSelfHealingUrls; class Post extends Model{ use HasSelfHealingUrls; // Optional custom model property (default is `slug`) protected $slug = 'title';}
Note: both packages have different implementations, so be sure to follow the respective README files to get started.
Luke's package also has the ability to customize the way a slug is joined to a model identifier; you can create your own custom IdentifierHandler
implementation. At the time of writing, the package ships with a HyphenIdentifierHandler
that looks like this:
namespace Lukeraymonddowning\SelfHealingUrls\IdentifierHandlers; use Illuminate\Support\Str;use Lukeraymonddowning\SelfHealingUrls\Contracts\IdentifierHandler; class HyphenIdentifierHandler implements IdentifierHandler{ public function joinToSlug(string $slug, string|int $identifier): string { return "{$slug}-{$identifier}"; } public function separateFromSlug(string $value): string { return Str::afterLast($value, '-'); }}
You can implement this interface to come up with your customized handler if you want to use a different identifier than a slug and a unique identifier separated by a hyphen (-
). I'd encourage you to watch Aaron's video to see what's going on under the hood in Laravel and try both implementations to see what you like.