In this article we are going to create slug from any input field. slug is useful search engine optimization and also from security perspective because in some case we use primary id or unique id of table to fetch the detail in page but its not recommended way to show number in URL. Showing ID in URL can be open to SQL injection which lead to website hacking.
There is 3 ways to create the slug in Laravel
- Create save event in model
- Slug using trait
- Slug using package
Create slug using save event
In this way we will create a event in every model to generate the slug and save into the table.
Step 1: Create a model
First step is to create the model using artisan command or you can choose your any model
php artisan make:model Post
it will generate a Post model in app\Model folder.
Step 2: Register the create event
Now, register a createed event on every new row creation
<?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 static function boot()
{
parent::boot();
static::created(function ($post) {
$post->slug = $post->generateUniqueSlug($post->title);
$post->save();
});
}
private function generateUniqueSlug($name,$counter=0,$slugField="slug")
{
$updatedName = $counter==0?$name:$name."-".$counter;
if (static::where($slugField,$slug = Str::slug($updatedName))->exists()) {
return $this->generateUniqueSlug($name,$counter+1);
}
return Str::slug($updatedName);
}
}
Here , we registered a event static::created
and then generated a unique slug by checking the existancy of slug recursively in database.
Step 3: Create the route and save post
This is the time to check our implementation, so we need to create the route and create a new post
<?php
use Illuminate\Support\Facades\Route;
use App\Models\Post;
Route::get('/check-slug',function(){
$post=new Post;
$post->title="This is a test";
$post->description="This is a test";
$post->save();
});
now we can check in browser and below is screenshot