Baike.dev
All toolsOnline toolsAI codingTrendingOpen sourceNewsSubmit
Log in
< Back to tools
E

eloquent-sluggable

> 后端框架
Open source

Easy creation of slugs for your Eloquent models in Laravel

4.0K stars0 likes0 views
WebsiteGitHub

About

Easy creation of slugs for your Eloquent models in Laravel

Eloquent-Sluggable

Easy creation of slugs for your Eloquent models in Laravel.

[!NOTE] These instructions are for the latest version of Laravel.
If you are using an older version, please install a version of the package that correlates to your Laravel version.

  • Eloquent-Sluggable
    • Background: What is a slug?
    • Installation
    • Updating your Eloquent Models
    • Usage
    • The SlugService Class
    • When Is A Model Slugged?
    • Events
    • Configuration
      • source
      • method
      • onUpdate
      • separator
      • unique
      • uniqueSuffix
      • firstUniqueSuffix
      • includeTrashed
      • reserved
      • maxLength
      • maxLengthKeepWords
      • slugEngineOptions
    • Short Configuration
    • Extending Sluggable
      • customizeSlugEngine
      • scopeWithUniqueSlugConstraints
      • scopeFindSimilarSlugs
    • SluggableScopeHelpers Trait
    • Route Model Binding
    • Bugs, Suggestions, Contributions and Support
    • Copyright and License

Background: What is a slug?

A slug is a simplified version of a string, typically URL-friendly. The act of "slugging" a string usually involves converting it to one case, and removing any non-URL-friendly characters (spaces, accented letters, ampersands, etc.). The resulting string can then be used as an identifier for a particular resource.

For example, if you have a blog with posts, you could refer to each post via the ID:

http://example.com/post/1
http://example.com/post/2

... but that's not particularly friendly (especially for SEO). You probably would prefer to use the post's title in the URL, but that becomes a problem if your post is titled "My Dinner With André & François", because this is pretty ugly too:

http://example.com/post/My+Dinner+With+Andr%C3%A9+%26+Fran%C3%A7ois

The solution is to create a slug for the title and use that instead. You might want to use Laravel's built-in Str::slug() method to convert that title into something friendlier:

http://example.com/post/my-dinner-with-andre-francois

A URL like that will make users happier (it's readable, easier to type, etc.).

For more information, you might want to read this description on Wikipedia.

Slugs tend to be unique as well. So if you write another post with the same title, you'd want to distinguish between them somehow, typically with an incremental counter added to the end of the slug:

http://example.com/post/my-dinner-with-andre-francois
http://example.com/post/my-dinner-with-andre-francois-1
http://example.com/post/my-dinner-with-andre-francois-2

This keeps the URLs unique.

The Eloquent-Sluggable package for Laravel aims to handle all of this for you automatically, with minimal configuration.

Installation

Depending on your version of Laravel, you should install a different version of the package.

[!NOTE] As of version 6.0, the package's version should match the Laravel version.

Laravel Version Package Version
13.0 ^13.0
12.0 ^12.0
11.0 ^11.0
10.0 ^10.0
9.0 ^9.0
8.0 ^8.0
7.0 ^7.0
6.0 ^6.0
5.8 4.8.*
5.7 4.7.*
5.6 4.5.*
5.5 4.4.*
5.4 4.2.*

Older versions of Laravel can use older versions of the package, although they are no longer supported or maintained. See CHANGELOG.md and UPGRADING.md for specifics, and be sure that you are reading the correct README.md for your version (GitHub displays the version in the master branch by default, which might not be what you want).

[!WARNING] Support for Laravel Lumen has been dropped.

  1. Install the package via Composer:

    bash
    composer require cviebrock/eloquent-sluggable

    The package will automatically register its service provider.

  2. Optionally, publish the configuration file if you want to change any defaults:

    bash
    php artisan vendor:publish --provider="Cviebrock\EloquentSluggable\ServiceProvider"

Updating your Eloquent Models

Your models should use the Sluggable trait, which has an abstract method sluggable() that you need to define. This is where any model-specific configuration is set (see Configuration below for details):

php
use Cviebrock\EloquentSluggable\Sluggable;

class Post extends Model
{
    use Sluggable;

    /**
     * Return the sluggable configuration array for this model.
     *
     * @return array
     */
    public function sluggable(): array
    {
        return [
            'slug' => [
                'source' => 'title'
            ]
        ];
    }
}

Of course, your model and database will need a column in which to store the slug. You can use slug or any other appropriate name you want; your configuration array will determine to which field the data will be stored. You will need to add the column (which should be NULLABLE) manually via your own migration.

That's it ... your model is now "sluggable"!

Usage

Saving a model is easy:

php
$post = Post::create([
    'title' => 'My Awesome Blog Post',
]);

So is retrieving the slug:

php
echo $post->slug;

[!NOTE] If you are replicating your models using Eloquent's replicate() method, the package will automatically re-slug the model afterwards to ensure uniqueness.

php
$post = Post::create([
    'title' => 'My Awesome Blog Post',
]);
// $post->slug is "my-awesome-blog-post"

$newPost = $post->replicate();
// $newPost->slug is "my-awesome-blog-post-1"

[!NOTE] Empty strings, non-strings or other "odd" source values will result in different slugs:

Source Value Resulting Slug
string string
empty string no slug will be set
null no slug will be set
0 "0"
1 "1"
false "0"
true "1"

The above values would be subject to any unique or other checks as well.

The SlugService Class

All the logic to generate slugs is handled by the \Cviebrock\EloquentSluggable\Services\SlugService class.

Generally, you don't need to access this class directly, although there is one static method that can be used to generate a slug for a given string without actually creating or saving an associated model.

php
use \Cviebrock\EloquentSluggable\Services\SlugService;

$slug = SlugService::createSlug(Post::class, 'slug', 'My First Post');

This would be useful for Ajax-y controllers or the like, where you want to show a user what the unique slug would be for a given test input, before actually creating a model. The first two arguments to the method are the model and slug field being tested, and the third argument is the source string to use for testing the slug.

You can also pass an optional array of configuration values as the fourth argument. These will take precedence over the normal configuration values for the slug field being tested. For example, if your model is configured to use unique slugs, but you want to generate the "base" version of a slug for some reason, you could do:

php
$slug = SlugService::createSlug(Post::class, 'slug', 'My First Post', ['unique' => false]);

When Is A Model Slugged?

Currently, the model is slugged on Eloquent's saving event. This means that the slug is generated before any new data is written to the database.

For new models, this means that the primary key has not yet been set, so it could not be used as part of the slug source, e.g.:

php
public function sluggable(): array
{
    return [
        'slug' => [
            'source' => ['title', 'id']
        ]
    ];
}

$model->id is null before the model is saved. The benefit of hooking into the saving event, however, is that we only needed to make one database query to save all the model's data, including the slug.

Optional, the model can be slugged on Eloquent's saved event.
This means that all the other model attributes will have already been persisted to the database and are available for use as slug sources. So the above configuration would work. The only drawback is that saving the model to the database requires one extra query: the first one to save all the non-slug fields, and then a second one to update just the slug field.

This behaviour is a breaking change, and likely won't affect most users (unless you are doing some pre-saving validation on a model's slug field). We feel the benefits outweigh the drawbacks, and so this will likely become the new default behaviour in a future major release of the package. Although, to make the transition easier, you can configure this behaviour via the sluggableEvent method the trait provides:

php
    public function sluggableEvent(): string
    {
        /**
         * Default behaviour -- generate slug before model is saved.
         */
        return SluggableObserver::SAVING;

        /**
         * Optional behaviour -- generate slug after model is saved.
         * This will likely become the new default in the next major release.
         */
        return SluggableObserver::SAVED;
    }

Keep in mind that you will need to use SluggableObserver::SAVED if you want to use your model's primary key as part of the source fields for your slugs.

Events

Sluggable models will fire two Eloquent model events: "slugging" and "slugged".

The "slugging" event is fired just before the slug is generated. If the callback from this event returns false, then the slugging is not performed. If anything else is returned, including null, then the slugging will be performed.

The "slugged" event is fired just after a slug is generated. It won't be called in the case where the model doesn't need slugging (as determined by the needsSlugging() method).

You can hook into either of these events just like any other Eloquent model event:

php
Post::registerModelEvent('slugging', static function($post) {
    if ($post->someCondition()) {
        // the model won't be slugged
        return false;
    }
});

Post::registerModelEvent('slugged', static function($post) {
    Log::info('Post slugged: ' . $post->getSlug());
});

Configuration

Configuration was designed to be as flexible as possible. You can set up defaults for all of your Eloquent models, and then override those settings for individual models.

By default, global configuration is set in the config/sluggable.php file. If a configuration isn't set, then the package defaults are used. Here is an example configuration, with all the default settings shown:

php
return [
    'source'             => null,
    'method'             => null,
    'onUpdate'           => false,
    'separator'          => '-',
    'unique

Issues· 0 open

View all issuesOpen on GitHub

No open issues yet, or sync has not completed.

> Tags

PHPeloquent-modelslaravelslug

No comments yet. Be the first to share.

> Details

PublishedAug 1, 2026
UpdatedSep 17, 2026
Category后端框架
PricingOpen source

> Related tools

N
Node.js
基于 V8 的 JavaScript 运行时
D
Django
Python 高级 Web 框架
S
Spring Boot
Java 生态主流微服务框架