Spatie, the company where I work, recently released a Laravel package called laravel-sluggable. It automatically creates unique slugs when saving a model.

To install that package you just need to put the provided Spatie\Sluggable\HasSlug-trait on all models that have slugs. The trait contains an abstract method getDefaultSlugOptions that should be implemented:

use Spatie\Sluggable\Slug;

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

This is the result when saving an Eloquent model.

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

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

Take a look at the readme of the package on GitHub to learn all the options.

There was already a very capable package by Colin Viebrock to create slugs. We’ve been using that package for all our projects since we started using Laravel. Colin’s package does a lot, but we’re only using a fraction of the functionality it provides. We’ve created our own sluggable package because we wanted to use something lightweight.

We also like to play around with the newest stuff. All our new projects will be using PHP 7 so it made sense to create a package that requires it. When you browse the code you’ll see usages of scalar type hints, return types, anonymous classes and the null coalescing operator.