Hi Dev,
Today, i we will show you laravel 8 create unique slug example. This article will give you simple example of laravel 8 create unique slug example. you will laravel 8 create unique slug example. In this article, we will implement a laravel 8 create unique slug example.
So let’s follow few step to create example of laravel 8 create unique slug example.
Slug Example
app/Models/Pages.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Pages extends Model
{
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'title', 'contant', 'slug'
];
protected static function boot()
{
parent::boot();
static::created(function ($post) {
$post->slug = $post->createSlug($post->title);
$post->save();
});
}
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\Pages;
use Illuminate\Http\Request;
class PageController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$page = Pages::create([
"title" => "Laravel CRUD"
]);
dd($page);
}
}
Output:
Laravel-CRUD Laravel-CRUD-2 Laravel-CRUD-3
I hope it will assist you…