Learn to Build a Chatbot with Laravel and BotMan!
Eloquent Sluggable Package
Laravel Packages / updated: May 29, 2018

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!

This appeared first on Laravel News
Laravel News Partners

Newsletter

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