Oh Dear is the all-in-one monitoring tool for your entire website. We monitor uptime, SSL certificates, broken links, scheduled tasks and more. You'll get a notifications for us when something's wrong. All that paired with a developer friendly API and kick-ass documentation. O, and you'll also be able to create a public status page under a minute. Start monitoring using our free trial now.

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.

You can follow me on these platforms:

On all these platforms, regularly share programming tips, and what I myself have learned in ongoing projects.

Every month 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.

Comments

What are your thoughts on "A PHP 7 / Laravel package to create slugs"?

Comments powered by Laravel Comments
Want to join the conversation? Log in or create an account to post a comment.