Eloquent Sluggable Package

Eloquent Sluggable Package

Adding unique slugs to your eloquent models is made simple through the Eloquent Sluggable package by Colin Viebrock.

The gist of using this package is making your Eloquent models “sluggable” through the Sluggable trait provided by the package, which defines an abstract sluggable() method you use to configure your model-specific configuration.

For example, if you wanted to use the title field on a model with the slug column:

use Cviebrock\EloquentSluggable\Sluggable;

class Post extends Model
{
    use Sluggable;

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

With the above model, an example usage from the README looks as follows:

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

$post->save();
$post->slug; // my-awesome-blog-post

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

I find it very convenient that the package automatically takes care of making posts unique if they happen to have the same title.

This package also ships with thoughtful configuration options to customize how slugs work. Here are the defaults:

return [
    'source'             => null,
    'maxLength'          => null,
    'maxLengthKeepWords' => true,
    'method'             => null,
    'separator'          => '-',
    'unique'             => true,
    'uniqueSuffix'       => null,
    'includeTrashed'     => false,
    'reserved'           => null,
    'onUpdate'           => false,
];

Check out the full readme on GitHub for many other examples, including working with relationship attributes to generate slugs and many other options.

You can install this package with the following composer command:

# For Laravel 5.6, use v4.5 of this package
# Check the readme for version matching
composer require cviebrock/eloquent-sluggable:^4.5

Thanks for the excellent package, Colin!


Filed in: Laravel Packages


Newsletter

Join the weekly newsletter and never miss out on new tips, tutorials, and more.

Laravel News Partners

Laravel Jobs

Senior Full-Stack Developer (PHP+JS)
Remote
The Interaction Design Foundation
Senior Laravel Developer
Remote
Sonar
Laravel / Vue.JS Developer - Join an amazing team!
Remote
JTR Solutions
Mid / Sen. Software Engineer
Clearwater, FL
ShineOn
Remote PHP / Laravel Developer
Remote
SpringboardVR
Senior PHP/Laravel Developer: Your Dream Work Environment
Remote
iPhone Photography School
Senior Laravel Developer
Leidseplein, Amsterdam
Orderchamp.com