2017 © Pedro Peláez
 

library laravel-sluggable

Generate slugs when saving Eloquent models

image

spatie/laravel-sluggable

Generate slugs when saving Eloquent models

  • Tuesday, May 8, 2018
  • by Spatie
  • Repository
  • 12 Watchers
  • 341 Stars
  • 130,647 Installations
  • PHP
  • 39 Dependents
  • 0 Suggesters
  • 64 Forks
  • 2 Open issues
  • 20 Versions
  • 21 % Grown

The README.md

Generate slugs when saving Eloquent models

Latest Version on Packagist MIT Licensed GitHub Workflow Status Total Downloads, (*1)

This package provides a trait that will generate a unique slug when saving any Eloquent model., (*2)

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

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

The slugs are generated with Laravels Str::slug method, whereby spaces are converted to '-'., (*3)

Spatie is a webdesign agency based in Antwerp, Belgium. You'll find an overview of all our open source projects on our website., (*4)

Support us

, (*5)

We invest a lot of resources into creating best in class open source packages. You can support us by buying one of our paid products., (*6)

We highly appreciate you sending us a postcard from your hometown, mentioning which of our package(s) you are using. You'll find our address on our contact page. We publish all received postcards on our virtual postcard wall., (*7)

Installation

You can install the package via composer: ``` bash composer require spatie/laravel-sluggable, (*8)


## Usage Your Eloquent models should use the `Spatie\Sluggable\HasSlug` trait and the `Spatie\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: ```php namespace App; use Spatie\Sluggable\HasSlug; use Spatie\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:, (*9)

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

class CreateYourEloquentModelTable extends Migration
{
    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();
        });
    }
}

Using slugs in routes

To use the generated slug in routes, remember to use Laravel's implicit route model binding:, (*10)

namespace App;

use Spatie\Sluggable\HasSlug;
use Spatie\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';
    }
}

Using multiple fields to create the slug

Want to use multiple field as the basis for a slug? No problem!, (*11)

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

Customizing slug generation

You can also pass a callable to generateSlugsFrom., (*12)

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

You can disable this behaviour by calling allowDuplicateSlugs., (*14)

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

Limiting the length of a slug

You can also put a maximum size limit on the created slug:, (*15)

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., (*16)

You can also use a custom separator by calling usingSeparator, (*17)

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

Setting the slug language

To set the language used by Str::slug you may call usingLanguage, (*18)

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

Overriding slugs

You can also override the generated slug just by setting it to another value than the generated slug., (*19)

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

Prevents slugs from being generated on some conditions

If you don't want to create the slug when the model has a state, you can use the skipGenerateWhen function., (*20)

public function getSlugOptions() : SlugOptions
{
    return SlugOptions::create()
        ->generateSlugsFrom('name')
        ->saveSlugsTo('slug')
        ->skipGenerateWhen(fn () => $this->state === 'draft');
}

Prevent slugs from being generated on creation

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

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

Prevent slug updates

Similarly, if you want to prevent the slug from being updated on model updates, call doNotGenerateSlugsOnUpdate()., (*22)

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

This can be helpful for creating permalinks that don't change until you explicitly want it to., (*23)

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

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

Regenerating slugs

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., (*24)

Preventing overwrites

You can prevent slugs from being overwritten., (*25)

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

Using scopes

If you have a global scope that should be taken into account, you can define this as well with extraScope. For example if you have a pages table containing pages of multiple websites and every website has it's own unique slugs., (*26)

public function getSlugOptions() : SlugOptions
{
    return SlugOptions::create()
        ->generateSlugsFrom('name')
        ->saveSlugsTo('slug')
        ->extraScope(fn ($builder) => $builder->where('scope_id', $this->scope_id));
}

Setting the slug suffix starting index

By default, suffix index starts from 1, you can set starting number., (*27)

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

Integration with laravel-translatable

You can use this package along with laravel-translatable to generate a slug for each locale. Instead of using the HasSlug trait, you must use the HasTranslatableSlug trait, and add the name of the slug field to the $translatable array. For slugs that are generated from a single field or multiple fields, you don't have to change anything else., (*28)

namespace App;

use Spatie\Sluggable\HasTranslatableSlug;
use Spatie\Sluggable\SlugOptions;
use Spatie\Translatable\HasTranslations;
use Illuminate\Database\Eloquent\Model;

class YourEloquentModel extends Model
{
    use HasTranslations, HasTranslatableSlug;

    public $translatable = ['name', 'slug'];

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

For slugs that are generated from a callable, you need to instantiate the SlugOptions with the createWithLocales method. The callable now takes two arguments instead of one. Both the $model and the $locale are available to generate a slug from., (*29)

namespace App;

use Spatie\Sluggable\HasTranslatableSlug;
use Spatie\Sluggable\SlugOptions;
use Spatie\Translatable\HasTranslations;
use Illuminate\Database\Eloquent\Model;

class YourEloquentModel extends Model
{
    use HasTranslations, HasTranslatableSlug;

    public $translatable = ['name', 'slug'];

    /**
     * Get the options for generating the slug.
     */
    public function getSlugOptions() : SlugOptions
    {
        return SlugOptions::createWithLocales(['en', 'nl'])
            ->generateSlugsFrom(function($model, $locale) {
                return "{$locale} {$model->id}";
            })
            ->saveSlugsTo('slug');
    }
}

Implicit route model binding

You can also use Laravels implicit route model binding inside your controller to automatically resolve the model. To use this feature, make sure that the slug column matches the routeNameKey.
Currently, only some database types support JSON operations. Further information about which databases support JSON can be found in the Laravel docs., (*30)

namespace App;

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

class YourEloquentModel extends Model
{
    use HasTranslations, HasTranslatableSlug;

    public $translatable = ['name', 'slug'];

    /**
     * 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';
    }
}

Find models by slug

For convenience, you can use the alias findBySlug to retrieve a model. The query will compare against the field passed to saveSlugsTo when defining the SlugOptions., (*31)

$model = Article::findBySlug('my-article');

findBySlug also accepts a second parameter $columns just like the default Eloquent find method., (*32)

Changelog

Please see CHANGELOG for more information what has changed recently., (*33)

Testing

bash composer test, (*34)

Contributing

Please see CONTRIBUTING for details., (*35)

Security

If you've found a bug regarding security please mail security@spatie.be instead of using the issue tracker., (*36)

Credits

License

The MIT License (MIT). Please see License File for more information., (*37)

The Versions

08/05 2018

dev-master

9999999-dev https://github.com/spatie/laravel-sluggable

Generate slugs when saving Eloquent models

  Sources   Download

MIT

The Requires

 

The Development Requires

spatie laravel-sluggable

15/02 2018

2.1.3

2.1.3.0 https://github.com/spatie/laravel-sluggable

Generate slugs when saving Eloquent models

  Sources   Download

MIT

The Requires

 

The Development Requires

spatie laravel-sluggable

08/02 2018

2.1.2

2.1.2.0 https://github.com/spatie/laravel-sluggable

Generate slugs when saving Eloquent models

  Sources   Download

MIT

The Requires

 

The Development Requires

spatie laravel-sluggable

28/01 2018

2.1.1

2.1.1.0 https://github.com/spatie/laravel-sluggable

Generate slugs when saving Eloquent models

  Sources   Download

MIT

The Requires

 

The Development Requires

spatie laravel-sluggable

28/01 2018

dev-analysis-86oN3W

dev-analysis-86oN3W https://github.com/spatie/laravel-sluggable

Generate slugs when saving Eloquent models

  Sources   Download

MIT

The Requires

 

The Development Requires

spatie laravel-sluggable

13/09 2017

2.1.0

2.1.0.0 https://github.com/spatie/laravel-sluggable

Generate slugs when saving Eloquent models

  Sources   Download

MIT

The Requires

 

The Development Requires

spatie laravel-sluggable

31/08 2017

2.0.0

2.0.0.0 https://github.com/spatie/laravel-sluggable

Generate slugs when saving Eloquent models

  Sources   Download

MIT

The Requires

 

The Development Requires

spatie laravel-sluggable

13/06 2016

1.2.0

1.2.0.0 https://github.com/spatie/laravel-sluggable

Generate slugs when saving Eloquent models

  Sources   Download

MIT

The Requires

 

The Development Requires

spatie laravel-sluggable

24/01 2016

1.1.0

1.1.0.0 https://github.com/spatie/laravel-sluggable

Generate slugs when saving Eloquent models

  Sources   Download

MIT

The Requires

 

The Development Requires

spatie laravel-sluggable

12/01 2016

1.0.2

1.0.2.0 https://github.com/spatie/laravel-sluggable

Generate slugs when saving Eloquent models

  Sources   Download

MIT

The Requires

 

The Development Requires

spatie laravel-sluggable

27/12 2015

1.0.1

1.0.1.0 https://github.com/spatie/laravel-sluggable

Generate slugs when saving Eloquent models

  Sources   Download

MIT

The Requires

 

The Development Requires

spatie laravel-sluggable

24/12 2015

1.0.0

1.0.0.0 https://github.com/spatie/laravel-sluggable

Generate slugs when saving Eloquent models

  Sources   Download

MIT

The Requires

 

The Development Requires

spatie laravel-sluggable

24/12 2015

0.0.1

0.0.1.0 https://github.com/spatie/eloquent-sluggable

An opinionated package to generate slugs for Eloquent models

  Sources   Download

MIT

The Requires

 

The Development Requires

spatie eloquent-sluggable