I'm currently organising Full Stack Europe. It's a conference in Antwerp, Belgium for developers who want to learn across the stack. You can use this link get your ticket with a nice discount.

A PHP 7 / Laravel package to create slugs

Original – by Freek Van der Herten – 2 minute read

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 the package you just need to put the provided Spatie\Sluggable\HasSlug-trait on all models that have slugs. The trait contains an abstract method getSlugOptions that should be implemented:

use Spatie\Sluggable\Slug;

public function getSlugOptions() : 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.

We're fully aware that requiring PHP 7 will mean that a lot of people won't be able to use the package. But gaining popularity isn't our main goal. We primarily create these packages for our own projects and for people who, like us, want to push forward.

Stay up to date with all things Laravel, PHP, and JavaScript.

Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.