Hello,This article will provide example of how to generate unique slug in laravel. you can 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. Let's get started with laravel generate slug before save.
you can easily create unique slug in laravel 6, laravel 7 and laravel 8 version.
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.
Let's see step by step to create unique slug in laravel example:
app/Models/Product.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
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();
});
}
/**
* 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\Product;
use Illuminate\Http\Request;
class ProductController extends Controller
{
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index()
{
$product = Product::create([
"title" => "Laravel 8 Image Upload"
]);
dd($product);
}
}
now if you create multiple time same title record then it will create slug as bellow:
laravel-8-image-upload
laravel-8-image-upload-2
laravel-8-image-upload-3
laravel-8-image-upload-4
now you can try it and check it.
i hope it can help you...
Do you like below Tutorials ?
- PHP Laravel 5.5 - import export data into excel and csv using maatwebsite
- Laravel 7.x and 6.x create custom facade example from scratch
- Node JS - Get Real time online users counter using socket io example
- PHP Laravel 7.x and 6.x - Bootstrap Admin Theme Integration example from scratch
- MySQL Query - How to select records of today to next Sunday ?
- Laravel 7.x and 6.x - username custom validation example
- Laravel 5.5 - Import Extract zip file using chumper/zipper package
- PHP Laravel Set Custom Validation Error Messages Example