Laravel 8 Create Unique Slug Tutorial Example

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...
Divyang Vadodariya
My name is Divyang Vadodariya. I'm a full-stack developer, entrepreneur and owner of RvSolutionStuff. I live in India and I love to write tutorials and tips that can help to other artisan. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap ,etc from the early stage.

We are Recommending you
- How To Mobile Device Detection In PHP Example
- Laravel 8 Create Unique Slug Tutorial Example
- React Google Column Chart Example
- How To Restore MySQL Database From SQL File Using PHP
- Convert String To Sentence Case In PHP Example
- PHP Tips & Tricks Some PHP Hacks Every Programmer Should Know
- Restore back deleted record in Laravel 8
- Axios Get Request in React Native Example
- Laravel Validation timezone Example
- Laravel Custom Function In Model
Copyright © 2023 www.RVSolutionStuff.com • All Rights Reserved