Skip to content

Instantly share code, notes, and snippets.

@rakibdevs
Last active June 7, 2020 10:54
Show Gist options
  • Save rakibdevs/f08cfae12488a187cf6167a91655f24d to your computer and use it in GitHub Desktop.
Save rakibdevs/f08cfae12488a187cf6167a91655f24d to your computer and use it in GitHub Desktop.
Laravel unique slug generator in Model Class. Add this function in your model class.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Post extends Model
{
//...................................
# verify and return custom slug string
public function slugify($text)
{
# remove ? mark from string
$slug = preg_replace('/\?/u', ' ', trim($text));
$slug = preg_replace('/\s+/u', '-', trim($slug));
# slug repeat check
$latest = $this->whereRaw("slug REGEXP '^{$slug}(-[0-9]+)?$'")
->latest('id')
->value('slug');
if($latest){
$pieces = explode('-', $latest);
$number = intval(end($pieces));
$slug .= '-' . ($number + 1);
}
return $slug;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment