In this article, we will provide example of how to generate unique slug in laravel. You will easily understand a concept of unique slug generator laravel example. I explained simply step by step laravel generate unique slug. if you want to see example of laravel create unique slug example then you are a right place.
So let's get started with laravel generate slug before save.
Sometime we need to create slug from title with your application. but you also need to create unique slug on that table. might be user will enter same title then it should automatically generate unique slug. i will give you simple example step by step how to generate unique slug in laravel using eloquent model events.
Below is the Product model file. In the model class, create createSlug()
method which create unique slug. Also create a boot() method which will trigger createSlug()
method everytime when new model is created.
<?php
namespace App\Models;
use Illuminate\Support\Str;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Factories\HasFactory;
class Product extends Model
{
use HasFactory;
protected $fillable = [
'title', 'detail', 'slug'
];
/**
* Boot the model.
*/
protected static function boot()
{
parent::boot();
static::created(function ($product) {
$product->slug = $product->createSlug($product->title);
$product->save();
});
}
/**
* create slug
*
* @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;
}
}
In the controller class, call create method of model class.
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* create a new product
*
* @return \Illuminate\Http\Response
*/
public function create()
{
$product = Product::create([
"title" => "Samsung s11 Pro"
]);
dd($product);
}
}
Now, it will create slug as below:
I hope it will help you.
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]
OnScroll Load More in Laravel 8 with Livewire Package
In this article, i will share with you h...Angular and Laravel CORS Access-Control-Allow-Origin Issues
I was woking on a Laravel API applicatio...Remove Whitespace Characters from Both Ends of a String
Sometimes you have a situation when you...How to Find the Max and Min Values of an Array in JavaScript
Use the apply() Method You can use th...Laravel 8 Default Password Validation Rules
Password is the most important data in a...