Easily Create Slug in Laravel for Posts

Why do We Need a Slug?

A slug is just a simplified string that comes at the end of a URL which usually refers to some specific page or post.

It makes your URL SEO and user-friendly. Slugs can also improve your ranking in the search engine as it makes it easy to predict the content of the page.

If you have worked with laravel then, normally you would refer each post via ID.

https://example.com/post/1

These URLs are not user-friendly. Instead, we can use some value like your post title to convert into slug using Str::slug() and you can get URLs like this.

https://example.com/post/sample-post

But slugs tend to be unique as well to identify their related post or page. So, you have to work on the extra logic to make the slug different from each other.

The Eloquent-Sluggable package for Laravel aims to handle all of this for you automatically, with minimal configuration.

Let’s Install and Setup Eloquent-Sluggable

First, Install the package via composer.

composer require cviebrock/eloquent-sluggable

Before this, make sure you have a unique “slug” column in your post table or whichever table you want to generate a slug for.

Now, you need to update your eloquent model. Your model should import the Sluggable trait and you need to define the abstract method sluggable().

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'
                 'separator'          => '-',
                 'unique'             => true,
                 'onUpdate'           => true,
                 'includeTrashed'     => false,
            ]
        ];
    }
}

In the code above, the sluggable method returns a nested slug array with several configurations for generating slug.

You can always check out the official repo documentation if you want to know more about the package here.

Alright, that’s it. That is all you need to do to implement slug in laravel with minimum effort.

Asmit Nepali, a Full Stack Developer, holds a Software Engineering degree from Gandaki College of Engineering and Science. Proficient in PHP Laravel, Vue.js, MySQL, Tailwind, Figma, and Git, he possesses a robust technical skill set.

Leave a Comment