PHPackages                             marshmallow/sluggable - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. marshmallow/sluggable

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

marshmallow/sluggable
=====================

Generate slugs when saving Eloquent models

v1.12.0(3mo ago)018.8k↓58%1[1 PRs](https://github.com/marshmallow-packages/sluggable/pulls)11MITPHPPHP ^7.4|^8.0CI failing

Since Sep 9Pushed 2w ago1 watchersCompare

[ Source](https://github.com/marshmallow-packages/sluggable)[ Packagist](https://packagist.org/packages/marshmallow/sluggable)[ Docs](https://gitlab.com/marshmallow-packages/sluggable)[ RSS](/packages/marshmallow-sluggable/feed)WikiDiscussions main Synced yesterday

READMEChangelog (9)Dependencies (8)Versions (21)Used By (11)

[![alt text](https://camo.githubusercontent.com/f5450f299f5713ce2f04dd5a1ba7ce9960ed4568b3574e4c4ee3cddc75477253/68747470733a2f2f6d617273686d616c6c6f772e6465762f63646e2f6d656469612f6c6f676f2d7265642d3233377834362e706e67 "marshmallow.")](https://camo.githubusercontent.com/f5450f299f5713ce2f04dd5a1ba7ce9960ed4568b3574e4c4ee3cddc75477253/68747470733a2f2f6d617273686d616c6c6f772e6465762f63646e2f6d656469612f6c6f676f2d7265642d3233377834362e706e67)

Generate slugs when saving Eloquent models
==========================================

[](#generate-slugs-when-saving-eloquent-models)

[![Latest Version on Packagist](https://camo.githubusercontent.com/544ddd1147a8304c6b6286c4620d6ad2cce18f208defe5a60e3d6981a18efa75/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6d617273686d616c6c6f772f736c75676761626c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/marshmallow/sluggable)[![Total Downloads](https://camo.githubusercontent.com/4987f4fa81b5bb9dfc7e16b72214e122e576edb12bc59129644836117c38baf0/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6d617273686d616c6c6f772f736c75676761626c652e7376673f7374796c653d666c61742d737175617265)](https://packagist.org/packages/marshmallow/sluggable)

This package was created by Spatie. We have forked it so we can add new features we need and so we are not dependend on Spatie before we can upgrade to new Laravel versions.

```
$model = new EloquentModel();
$model->name = 'activerecord is awesome';
$model->save();

echo $model->slug; // ouputs "activerecord-is-awesome"
```

The slugs are generated with Laravels `Str::slug` method, whereby spaces are converted to '-'.

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require marshmallow/sluggable
```

The package registers its `Marshmallow\Sluggable\SluggableServiceProvider` automatically through Laravel's package discovery, so there is nothing else to wire up.

Usage
-----

[](#usage)

Your Eloquent models should use the `Marshmallow\Sluggable\HasSlug` trait and the `Marshmallow\Sluggable\SlugOptions` class.

The trait contains an abstract method `getSlugOptions()` that you must implement yourself.

Your models' migrations should have a field to save the generated slug to.

Here's an example of how to implement the trait:

```
namespace App;

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

class YourEloquentModel extends Model
{
    use HasSlug;

    /**
     * Get the options for generating the slug.
     */
    public function getSlugOptions() : SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('name')
            ->saveSlugsTo('slug');
    }
}
```

With its migration:

```
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateYourEloquentModelTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('your_eloquent_models', function (Blueprint $table) {
            $table->increments('id');
            $table->string('slug'); // Field name same as your `saveSlugsTo`
            $table->string('name');
            $table->timestamps();
        });
    }
}
```

To use the generated slug in routes, remember to use Laravel's [implicit route model binding](https://laravel.com/docs/routing#implicit-binding):

```
namespace App;

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

class YourEloquentModel extends Model
{
    use HasSlug;

    /**
     * Get the options for generating the slug.
     */
    public function getSlugOptions() : SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('name')
            ->saveSlugsTo('slug');
    }

    /**
     * Get the route key for the model.
     *
     * @return string
     */
    public function getRouteKeyName()
    {
        return 'slug';
    }
}
```

Want to use multiple field as the basis for a slug? No problem!

```
public function getSlugOptions() : SlugOptions
{
    return SlugOptions::create()
        ->generateSlugsFrom(['first_name', 'last_name'])
        ->saveSlugsTo('slug');
}
```

You can also pass a `callable` to `generateSlugsFrom`.

By default the package will generate unique slugs by appending '-' and a number, to a slug that already exists.

You can disable this behaviour by calling `allowDuplicateSlugs`.

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

You can also put a maximum size limit on the created slug:

```
public function getSlugOptions() : SlugOptions
{
    return SlugOptions::create()
        ->generateSlugsFrom('name')
        ->saveSlugsTo('slug')
        ->slugsShouldBeNoLongerThan(50);
}
```

The slug may be slightly longer than the value specified, due to the suffix which is added to make it unique. When no maximum is set, slugs are capped at 250 characters by default.

You can also use a custom separator by calling `usingSeparator`

```
public function getSlugOptions() : SlugOptions
{
    return SlugOptions::create()
        ->generateSlugsFrom('name')
        ->saveSlugsTo('slug')
        ->usingSeparator('_');
}
```

To set the language used by `Str::slug` you may call `usingLanguage`

```
public function getSlugOptions() : SlugOptions
{
    return SlugOptions::create()
        ->generateSlugsFrom('name')
        ->saveSlugsTo('slug')
        ->usingLanguage('nl');
}
```

You can also override the generated slug just by setting it to another value than the generated slug.

```
$model = EloquentModel:create(['name' => 'my name']); //slug is now "my-name";
$model->slug = 'my-custom-url';
$model->save(); //slug is now "my-custom-url";
```

If you don't want to create the slug when the model is initially created you can set use the `doNotGenerateSlugsOnCreate()` function.

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

Similarly, if you want the slug to be generated again on model updates, call `generateSlugsOnUpdate()`.

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

This can be helpful for creating permalinks that don't change until you explicitly want it to.

```
$model = EloquentModel:create(['name' => 'my name']); //slug is now "my-name";
$model->save();

$model->name = 'changed name';
$model->save(); //slug stays "my-name"
```

If you want to explicitly update the slug on the model you can call `generateSlug()` on your model at any time to make the slug according to your other options. Don't forget to `save()` the model to persist the update to your database.

### Translatable slugs

[](#translatable-slugs)

If you generate localized routes, let your model implement the `Marshmallow\Sluggable\Contracts\TranslatableSlug` contract. When a model implements this contract and no explicit language has been set on the slug options, the package falls back to the locale returned by `request()->getTranslatableLocale()` when calling `Str::slug`.

```
use Marshmallow\Sluggable\HasSlug;
use Marshmallow\Sluggable\SlugOptions;
use Illuminate\Database\Eloquent\Model;
use Marshmallow\Sluggable\Contracts\TranslatableSlug;

class YourEloquentModel extends Model implements TranslatableSlug
{
    use HasSlug;

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

You can also seed the available locales up front with `SlugOptions::createWithLocales([...])`.

Events
------

[](#events)

Whenever a slug is created, changed or removed the package dispatches an event (after the database transaction has committed):

EventDispatched when`Marshmallow\Sluggable\Events\SlugWasCreated`A model with a slug is created.`Marshmallow\Sluggable\Events\SlugHasBeenChanged`An existing model's slug field changes on update.`Marshmallow\Sluggable\Events\SlugWasDeleted`A model with a slug is deleted.Each event exposes the affected model through its public `$model` property.

Out of the box these events are handled by `Marshmallow\Sluggable\Listeners\RunArtisanCommands`, which refreshes cached routes so slug-based URLs stay in sync. By default it runs `route:clear` and `route:cache`, but only when the application's routes are actually cached. You can customize this per model:

- Override `getArtisanCommands(): array` to change which commands run.
- Override `runArtisanCommandsWhen(): bool` to control when they run (defaults to `app()->routesAreCached()`).
- Define a `runSluggableArtisanCommands()` method to take over the behaviour entirely.

Redirects
---------

[](#redirects)

If your model is also redirectable (it exposes a `redirectable()` relation, e.g. via the `marshmallow/redirectable` package), the package will automatically register a redirect from the old slug to the new one whenever the slug changes, and remove those redirects when the model is deleted.

Testing
-------

[](#testing)

```
composer test
```

Changelog
---------

[](#changelog)

Please see [CHANGELOG](CHANGELOG.md) for more information what has changed recently.

Security
--------

[](#security)

If you discover any security related issues, please email  instead of using the issue tracker.

Credits
-------

[](#credits)

- [Stef van Esch](https://github.com/marshmallow-packages)
- [Freek Van der Herten](https://github.com/freekmurze)
- [All Contributors](../../contributors)

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE.md) for more information.

###  Health Score

54

—

FairBetter than 96% of packages

Maintenance90

Actively maintained with recent releases

Popularity27

Limited adoption so far

Community21

Small or concentrated contributor base

Maturity69

Established project with proven stability

 Bus Factor1

Top contributor holds 77.8% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~134 days

Recently: every ~147 days

Total

16

Last Release

107d ago

PHP version history (3 changes)v1.0.0PHP ^7.4

v1.1.0PHP ^7.4|^8.0

v1.4.0PHP ^7.4|^8.0|^8.1

### Community

Maintainers

![](https://www.gravatar.com/avatar/be33d2624e24c516e73892b0929447cc762f3622c024ab8d0d2a59042e5d2c7f?d=identicon)[marshmallow](/maintainers/marshmallow)

---

Top Contributors

[![stefvanesch](https://avatars.githubusercontent.com/u/46725619?v=4)](https://github.com/stefvanesch "stefvanesch (77 commits)")[![LTKort](https://avatars.githubusercontent.com/u/2412670?v=4)](https://github.com/LTKort "LTKort (13 commits)")[![dependabot[bot]](https://avatars.githubusercontent.com/in/29110?v=4)](https://github.com/dependabot[bot] "dependabot[bot] (9 commits)")

---

Tags

laravel-sluggablemarshmallow

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/marshmallow-sluggable/health.svg)

```
[![Health](https://phpackages.com/badges/marshmallow-sluggable/health.svg)](https://phpackages.com/packages/marshmallow-sluggable)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3355.3M346](/packages/psalm-plugin-laravel)[api-platform/laravel

API Platform support for Laravel

58171.4k14](/packages/api-platform-laravel)[wearepixel/laravel-cart

A cart implementation for Laravel

1374.8k](/packages/wearepixel-laravel-cart)[aedart/athenaeum

Athenaeum is a mono repository; a collection of various PHP packages

245.2k](/packages/aedart-athenaeum)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
