Skip to content

Log-zz-ikIO/laravel-sluggable

 
 

Repository files navigation

Generate slugs when saving Eloquent models

Latest Version on Packagist Software License Build Status SensioLabsInsight Quality Score Total Downloads

This package provides as trait that will generate a unique slug when saving model. The trait can be applied on any model.

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

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

The slug will be generated with Laravels str_slug-method. Spaces will be converted to '-'.

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

Installation

You can install the package via composer:

$ composer require spatie/laravel-sluggable

Usage

The package provides a Spatie\Sluggable\HasSlug-trait that can be applied on any Eloquent model.

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

This is the most simple implementation:

use Spatie\Sluggable\Slug;

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

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

use Spatie\Sluggable\Slug

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

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.

use Spatie\Sluggable\Slug

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

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

use Spatie\Sluggable\Slug

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

The slug can be slightly longer that the value specified as the suffix to make it unique is added.

Change log

Please see CHANGELOG for more information what has changed recently.

Testing

$ composer test

Contributing

Please see CONTRIBUTING for details.

Security

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

Credits

About Spatie

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

License

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

About

An opinionated package to create slugs for Eloquent models

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages

  • PHP 100.0%