How to Generate Unique slug in Laraval 7.x Example

  1204 views   1 year ago Laravel

Want to engender unique slug in Laravel? Its fairly facile. Lets endeavor.
First of all you should have a `slug` column in your Model. Suppose you have Post model. integrate this code inside model class,
Now you can call slugify method anywhere utilizing post object for engender unique slug. Surmise, you optate to store a post with slug. in PostController you can facilely engender slug and store into database.

<?php
namespace App;

use Illuminate\Database\Eloquent\Model;

class Post extends Model
{    
    # verify and return custom slug string
    public function slugify($text)
    {
        # remove ? mark from string
        $slug = preg_replace('/\?/u', ' ', trim($text));
        $slug = preg_replace('/\s+/u', '-', trim($slug));

        # slug repeat check
        $latest = $this->whereRaw("slug REGEXP '^{$slug}(-[0-9]+)?$'")
                       ->latest('id')
                       ->value('slug');

        if($latest){
            $pieces = explode('-', $latest);
            $number = intval(end($pieces));
            $slug .= '-' . ($number + 1);
        }       

        return $slug;
    }

}
<?php
namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Post;

class PostController extends Controller
{
    public function store(Request $request)
    {
        $post = new Post();
        //..............................
        /* unique slug example 
         * my name is khan => my-name-is-khan
         */
        $post->slug = $post->slugify($request->title); // unique slug generator
        //..............................
        $post->save();
    }
}

i hope you like this article.

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on [email protected]

Related Articles