DEV Community

Cover image for Laravel Slugable
Raymond Baghumian
Raymond Baghumian

Posted on

Laravel Slugable

Laravel Slugable is a lightweight Laravel trait that automatically generates slugs from model fields like title, name, or any custom source — and stores it in a customizable destination field such as slug, etc.

Perfect for blogs, e-commerce, CMS, or any app that needs clean, readable, SEO-friendly URLs.

Features

  • Auto-generate slug on model creation

  • Optional re-generation on model update

  • Customizable source and destination fields

  • No external dependencies

  • Support for Persian and Arabic Numbers to slug

Installation

composer require rayiumir/laravel-slugable
Enter fullscreen mode Exit fullscreen mode

After Publish Files:

php artisan vendor:publish --provider="Rayiumir\\Slugable\\ServiceProvider\\SlugableServiceProvider"
Enter fullscreen mode Exit fullscreen mode

How to use

Calling HasSlugable in Models Post.php.

class Post extends Model
{
    use HasSlugable;
}
Enter fullscreen mode Exit fullscreen mode

Provided that the title and slug fields are in the database.

If you want to use a custom field for slug generation, you can easily do that:

class Post extends Model
{
    use HasSlugable;

    protected $slugSourceField = 'name';
    protected $slugDestinationField = 'slug';
}
Enter fullscreen mode Exit fullscreen mode

Example

$post = new Post();
$post->title = 'Laravel 12';
$post->save();

echo $post->slug; // Output: laravel-12
Enter fullscreen mode Exit fullscreen mode

Image description

Why Use This?

Because:

  • You don’t want to install a full package just for slug generation.
  • You need quick setup and full control.
  • You want to save time and avoid boilerplate logic in your models.

Top comments (0)