Easily Create Slug in Laravel for Posts

Why do we need slug?

Slug is just a simplified string that comes at the end of 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 definitely 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.

Lets 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 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 a number of configurations for generating slug.

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

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

Leave a Comment