Stable, collision-safe slugs in Laravel PHP
Source, scope, and compatibility
Reference Spatie's MIT-licensed spatie/laravel-sluggable 6.0.1 at f1e6344e16dd3dbbcc60ffd853aec58e721d33d5. Read src/HasSlug.php, src/SlugOptions.php, src/Actions/GenerateSlugAction.php, and slug/uniqueness tests. Retain the upstream MIT notice for copied/adapted code. PHP framework baseline: 1b57d01aa866b042a75683bd9ef3517008c632fc. The source package version requires PHP 8.4 and Illuminate 13; an older application's behavior must be checked against its own pinned package, not assumed identical.
Inline one model's title-to-slug assignment and collision policy. Preserve existing stored slugs and route resolution. Multilingual JSON slugs, custom suffix generators, self-healing URLs, UUID/ULID variants, and automatic redirect history are out of scope unless the app already uses them. This is not a claim of full package parity; validate it in your app with the checks below.
Behavior that matters
The package runs on create/update, delegates normalization to Str::slug with separator/language options, supports manual overrides and skip/prevent-overwrite rules, and excludes the current record during uniqueness checks. At this source, default uniqueness searches remove global scopes, include soft-deleted rows, and may apply extraScopeCallback. Suffixes start at 1 by default; maximumLength truncates the source before slugification, so it is not a blanket final-length guarantee once suffixes are appended.
Inventory getSlugOptions, generateSlug, route-key overrides, old redirects, explicit slug writes, and import/queue paths. Choose whether slug edits follow title changes or remain stable. Package defaults regenerate on update; “keep an established URL” is a deliberate policy choice, not a statement of the default.
Application-owned assignment
- Keep existing slug values and route keys untouched. Put new assignment in the model's existing write action/observer so HTTP, jobs, and imports cannot bypass it. Do not mass-assign slug or tenant ownership from arbitrary requests.
- Preserve the chosen normalization with
Str::slug($title, '-', 'en')or the app's existing language/separator. Capture fixtures for punctuation, accents, non-Latin text, emoji-only/empty input, and manual overrides. Choose a documented nonempty fallback only if it does not silently change existing behavior. - Define one uniqueness scope used consistently by lookup, collision checks, and a database unique constraint: global slug, or
(tenant_id, slug)if routes include tenant identity. Match soft-delete/restore policy. Do not assume a global scope is an authorization or uniqueness guarantee; do not add a constraint until duplicates and deployment effects have been reviewed. - Generate candidates from a fixed base:
post,post-1,post-2, notpost-1-2. Exclude the current record on update. Reserve final column length for the suffix and truncate at a valid character boundary. Changing upstream's source-length behavior is an intentional safety improvement to document. exists()followed bysave()is racy. Enforce the chosen database uniqueness constraint and use bounded retries of the whole write transaction on a collision of that specific constraint. On PostgreSQL a unique violation aborts its transaction; catching it and continuing queries inside that same failed transaction does not recover it. Do not retry unrelated constraints or regenerate a user-supplied override without an explicit policy.- Preserve manual overrides, skip rules, and stable-on-update behavior deliberately. If changing a stored slug is allowed, handle redirects or broken old URLs as an explicit application feature. Never rewrite every existing slug during the package removal.
Pure candidate construction only; persistence, scope, and retry belong to the write action:
$base = Str::slug($title, '-', 'en');
// Reject an empty result or apply the explicitly chosen application fallback.
$candidate = $attempt === 0 ? $base : $base.'-'.$attempt;
Verification before removal
- Create title
Hello Worldrepeatedly; expecthello-world,hello-world-1, then the next available suffix under the chosen policy. - Update the original without a slug change; it must not collide with itself. A title-only update preserves or changes the slug exactly as declared.
- Test
Café,a@b, punctuation, non-Latin and emoji-only names, a title at the length boundary, and a suffix crossing 9 to 10. - Test manual overrides, another tenant with the same title, soft-deleted collisions, and restore behavior against the actual constraint.
- Start simultaneous creates through independent production-driver connections. Both succeed with distinct valid slugs or return the documented bounded conflict; no duplicate is committed.
- Force an unrelated unique violation; it must fail immediately, not enter the slug retry loop.
- Existing URLs continue resolving to the same record; unauthorized tenants cannot resolve another tenant's slug.
Run the app's slug/route feature tests, for example php artisan test --filter=Slug, plus a real-database concurrency case. Compare the declared subset with the package-backed path. Only after the inventory and these checks pass should you remove HasSlug, migrate remaining listeners/options, and check composer why spatie/laravel-sluggable. Record the results with the change.