Skip to content

Instantly share code, notes, and snippets.

@syofyanzuhad
Created January 27, 2022 14:43
Show Gist options
  • Save syofyanzuhad/ea6b12789c942af108bce8a4bf88f18e to your computer and use it in GitHub Desktop.
Save syofyanzuhad/ea6b12789c942af108bce8a4bf88f18e to your computer and use it in GitHub Desktop.
Make your model sluggable
<?php
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Berita extends Model
{
use HasFactory;
protected $table = 'berita';
protected $fillable = [
'penulis_id',
'title',
'slug',
];
public static function boot()
{
parent::boot();
static::creating(function ($model) {
// produce a slug based on the activity title
$slug = Str::slug($model->title);
// check to see if any other slugs exist that are the same & count them
$count = static::whereRaw("slug RLIKE '^{$slug}(-[0-9]+)?$'")->count();
// if other slugs exist that are the same, append the count to the slug
$model->slug = $count ? "{$slug}-{$count}" : $slug;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment