10-Apr-2023
.
Admin
Hi Guys,
In this example,I will lean you how to create unique slug in laravel.you can easy nad simply create unique slug in laravel.
In this tutorial, I will give you an example of How to Generate Unique Slug in Laravel, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.
Let's see step by step to create unique slug in laravel example:
app/Models/Post.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Post extends Model
{
use HasFactory;
protected $fillable = [
'title','slug'
];
/**
* Boot the model.
*/
protected static function boot()
{
parent::boot();
static::created(function ($post) {
$post->slug = $post->createSlug($post->title);
$post->save();
});
}
/**
* Write code on Method
*
* @return response()
*/
private function createSlug($title){
if (static::whereSlug($slug = Str::slug($title))->exists()) {
$max = static::whereTitle($title)->latest('id')->skip(1)->value('slug');
if (is_numeric($max[-1])) {
return preg_replace_callback('/(\d+)$/', function ($mathces) {
return $mathces[1] + 1;
}, $max);
}
return "{$slug}-2";
}
return $slug;
}
}
Controller Code:
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$post = Post::create([
"title" => "Laravel Livewire CRUD"
]);
dd($post);
}
}
now if you create multiple time same title record then it will create slug as bellow:
Laravel-Livewire-CRUD
Laravel-Livewire-CRUD-2
Laravel-Livewire-CRUD-3
It will help you...
#Laravel
#Laravel 6