Convert Figma logo to code with AI

spatie logolaravel-sluggable

An opinionated package to create slugs for Eloquent models

1,371
179
1,371
1

Top Related Projects

2,867

Converts a string to a slug. Includes integrations for Symfony, Silex, Laravel, Zend Framework 2, Twig, Nette and Latte.

A Laravel package for multilingual models

A Hashids bridge for Laravel

Quick Overview

Laravel-sluggable is a package for Laravel that provides an easy way to create slugs for your Eloquent models. It automatically generates URL-friendly slugs based on one or more attributes of your model, ensuring uniqueness and customization options.

Pros

  • Easy integration with Laravel Eloquent models
  • Customizable slug generation with multiple source fields
  • Automatic handling of slug uniqueness
  • Supports translatable slugs for multilingual applications

Cons

  • Limited to Laravel framework
  • May require additional configuration for complex slug generation scenarios
  • Potential performance impact on large datasets when checking for uniqueness
  • Might conflict with other packages that modify Eloquent model behavior

Code Examples

  1. Basic usage with a single source field:
use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;

class Post extends Model
{
    use HasSlug;

    public function getSlugOptions() : SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('title')
            ->saveSlugsTo('slug');
    }
}
  1. Using multiple source fields for slug generation:
public function getSlugOptions() : SlugOptions
{
    return SlugOptions::create()
        ->generateSlugsFrom(['title', 'subtitle'])
        ->saveSlugsTo('slug');
}
  1. Customizing slug generation with a callback:
public function getSlugOptions(): SlugOptions
{
    return SlugOptions::create()
        ->generateSlugsFrom('title')
        ->saveSlugsTo('slug')
        ->slugsShouldBeNoLongerThan(50)
        ->usingSeparator('_')
        ->usingLanguage('nl')
        ->withCustomSlugGenerator(function(string $string): string {
            return strtoupper($string);
        });
}

Getting Started

  1. Install the package via Composer:

    composer require spatie/laravel-sluggable
    
  2. Add the HasSlug trait to your Eloquent model and implement the getSlugOptions() method:

use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;

class YourModel extends Model
{
    use HasSlug;

    public function getSlugOptions() : SlugOptions
    {
        return SlugOptions::create()
            ->generateSlugsFrom('name')
            ->saveSlugsTo('slug');
    }
}
  1. Use the model as usual, and the slug will be automatically generated and saved when the model is created or updated.

Competitor Comparisons

2,867

Converts a string to a slug. Includes integrations for Symfony, Silex, Laravel, Zend Framework 2, Twig, Nette and Latte.

Pros of Slugify

  • Framework-agnostic, can be used in any PHP project
  • Supports a wide range of languages and special characters
  • Highly customizable with options for custom rules and translations

Cons of Slugify

  • Requires manual integration with Laravel models
  • Lacks built-in features for handling duplicate slugs in a database context

Code Comparison

Slugify:

use Cocur\Slugify\Slugify;

$slugify = new Slugify();
$slug = $slugify->slugify('Hello World!');

Laravel-sluggable:

use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;

class Post extends Model
{
    use HasSlug;

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

Key Differences

  • Laravel-sluggable is specifically designed for Laravel, offering seamless integration with Eloquent models
  • Slugify provides more flexibility for use in various PHP projects but requires more manual setup in Laravel
  • Laravel-sluggable handles duplicate slugs automatically, while Slugify requires custom implementation
  • Slugify offers more extensive language support out of the box

Both libraries are well-maintained and popular choices for slug generation in PHP projects, with the choice depending on the specific requirements of your project and whether you're working within the Laravel framework.

A Laravel package for multilingual models

Pros of laravel-translatable

  • Supports multiple languages and translations for model attributes
  • Offers flexible translation storage options (JSON, separate tables)
  • Provides scopes for querying translated models efficiently

Cons of laravel-translatable

  • More complex setup and configuration compared to laravel-sluggable
  • Potentially higher database overhead due to additional translation tables
  • May require more careful handling of fallback languages and translations

Code Comparison

laravel-translatable:

use Astrotomic\Translatable\Translatable;

class Post extends Model
{
    use Translatable;

    public $translatedAttributes = ['title', 'content'];
}

laravel-sluggable:

use Spatie\Sluggable\HasSlug;

class Post extends Model
{
    use HasSlug;

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

While laravel-translatable focuses on multilingual content management, laravel-sluggable specializes in generating URL-friendly slugs. laravel-translatable offers more comprehensive internationalization features but requires additional setup. laravel-sluggable provides a simpler solution for creating slugs from model attributes, making it more suitable for projects that don't require extensive multilingual support.

A Hashids bridge for Laravel

Pros of laravel-hashids

  • Provides unique, non-sequential identifiers for database records
  • Offers better security by obfuscating actual database IDs
  • Allows for easy decoding of hashids back to original IDs

Cons of laravel-hashids

  • Requires additional setup and configuration
  • May increase complexity in URL structure and database queries
  • Not suitable for SEO-friendly URLs like slugs

Code Comparison

laravel-hashids:

use Vinkla\Hashids\Facades\Hashids;

$id = 1;
$hashid = Hashids::encode($id);
$decodedId = Hashids::decode($hashid)[0];

laravel-sluggable:

use Spatie\Sluggable\HasSlug;
use Spatie\Sluggable\SlugOptions;

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

While laravel-hashids focuses on generating unique, encoded identifiers for database records, laravel-sluggable is designed to create SEO-friendly URL slugs based on model attributes. laravel-hashids offers better security and obfuscation of IDs, but laravel-sluggable provides more natural, readable URLs. The choice between the two depends on the specific requirements of your project, such as security needs, URL structure preferences, and SEO considerations.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

Generate slugs when saving Eloquent models

Latest Version on Packagist MIT Licensed GitHub Workflow Status Total Downloads

This package provides a trait that will generate a unique slug when saving any Eloquent model.

$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 '-'.

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

Support us

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.

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.

Installation

You can install the package via composer:

composer require spatie/laravel-sluggable

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:

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:

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:

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!

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.

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();
}

Limiting the length of a slug

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.

You can also use a custom separator by calling usingSeparator

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

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.

$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.

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.

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().

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.

$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.

Preventing overwrites

You can prevent slugs from being overwritten.

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.

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.

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.

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.

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.

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.

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

findBySlug also accepts a second parameter $columns just like the default Eloquent find method.

Changelog

Please see CHANGELOG for more information what has changed recently.

Testing

composer test

Contributing

Please see CONTRIBUTING for details.

Security

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

Credits

License

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