惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

V
V2EX
Y
Y Combinator Blog
博客园_首页
V
Visual Studio Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
阮一峰的网络日志
阮一峰的网络日志
Hugging Face - Blog
Hugging Face - Blog
宝玉的分享
宝玉的分享
B
Blog
博客园 - 三生石上(FineUI控件)
小众软件
小众软件
WordPress大学
WordPress大学
L
LangChain Blog
爱范儿
爱范儿
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
P
Proofpoint News Feed
Blog — PlanetScale
Blog — PlanetScale
C
Check Point Blog
博客园 - 聂微东
云风的 BLOG
云风的 BLOG
Microsoft Security Blog
Microsoft Security Blog
博客园 - 叶小钗
酷 壳 – CoolShell
酷 壳 – CoolShell
H
Help Net Security

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Laravel Sluggable Package: Finally, Opinionated Slug Gene...
S M Tahosin · 2026-04-28 · via DEV Community

S M Tahosin

Cover

So, Laravel News just highlighted the new Laravel Sluggable package for Eloquent models. It's an opinionated, automatic slug generation solution, and honestly, I think it's about damn time we got something this straightforward built into the ecosystem.

Why this matters for web developers

If you're building any kind of content-driven Laravel app, you know the drill: you need clean, readable URLs. That means transforming a post title like "My Awesome Blog Post With Special Characters!" into "my-awesome-blog-post-with-special-characters". This isn't just about aesthetics; good slugs are crucial for SEO, making your content more discoverable for search engines. But hand-rolling slug generation every time, dealing with uniqueness, and updating them when titles change? That's a repetitive chore. This package takes that entire headache away, letting you focus on the actual content and features, not string manipulation. We're talking about saving hours across a project with just a few models.

The technical reality

Setting this up is pretty painless. You pull in the package, add a trait to your Eloquent model, and tell it which field to use for the slug source. It's smart enough to handle uniqueness by default, appending numbers if needed. Let's say you have a Post model and want to slugify its title field. Here's how you'd get it running:

// In your Post model (app/Models/Post.php)
namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;

class Post extends Model
{
    use HasSlug;

    protected $fillable = ['title', 'content', 'slug'];

    public function getSlugOptions() : SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('title')
            ->saveSlugsTo('slug');
    }
}

Enter fullscreen mode Exit fullscreen mode

And you'll need to add a slug column to your database table. A simple migration handles that:

// In your migration file (e.g., 2023_10_27_create_posts_table.php)
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up() : void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('title');
            $table->text('content');
            $table->string('slug')->unique(); // The magic happens here
            $table->timestamps();
        });
    }

    public function down() : void
    {
        Schema::dropIfExists('posts');
    }
};

Enter fullscreen mode Exit fullscreen mode

Now, whenever you create or update a post, the slug field gets populated automatically. It's that easy to add a core feature.

What I'd actually do today

  1. Install the package: composer require spatie/laravel-sluggable. Spatie packages are usually solid, so I trust this one out of the box.
  2. Add a slug column: Create a migration to add a string column named slug to my relevant Eloquent models, making sure it's unique().
  3. Implement HasSlug trait: Drop use HasSlug; and the getSlugOptions() method into each model that needs slugs.
  4. Configure SlugOptions: Specify generateSlugsFrom() to point to the correct source attribute (like title or name) and saveSlugsTo() to the new slug column.
  5. Test it: Create a few new records, update some existing ones, and verify the slugs are generated correctly and are unique.

Gotchas & unknowns

While the package is great, there are always things to watch for. If you've got existing data without slugs, this package won't magically backfill them; you'll need a separate script or a php artisan tinker session to regenerate slugs for old records. Also, if your title field changes, the slug will regenerate by default. That's usually what you want, but if you need permanent, unchanging slugs even after a title edit, you'll need to configure it with doNotGenerateSlugsOnUpdate(). And while it handles uniqueness, complex edge cases with very similar titles might still produce less than ideal slugs, like my-post-1, my-post-2, my-post-3. It's a common issue, not unique to this package. Plus, this specific version I'm looking at doesn't handle multilingual slugs out of the box, which can be a real pain for global applications.

What's your preferred approach for managing slugs in your Laravel projects? Are you rolling your own, or does a package like this make more sense for your workflow?