Your destination for complete Tech news

How to create unique slug in Laravel?

23 0
< 1 min read

To create a unique slug in Laravel, you can use the str_slug function and the unique method on the Eloquent model.

Here’s an example of how you might create a unique slug for a blog post model:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = ['title', 'body'];

    /**
     * Boot the model.
     *
     * @return void
     */
    protected static function boot()
    {
        parent::boot();

        static::creating(function ($post) {
            $post->slug = str_slug($post->title);

            if (static::whereSlug($post->slug)->exists()) {
                $post->slug = "{$post->slug}-" . time();
            }
        });
    }
}

This model will automatically create a unique slug for each blog post when it is created. If a post with the same slug already exists, the model will append a timestamp to the slug to make it unique.

Leave A Reply

Your email address will not be published.

sixteen + 16 =

This site uses Akismet to reduce spam. Learn how your comment data is processed.