Created
January 27, 2022 14:43
-
-
Save syofyanzuhad/ea6b12789c942af108bce8a4bf88f18e to your computer and use it in GitHub Desktop.
Make your model sluggable
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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