Last active
June 7, 2020 10:54
-
-
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.
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 | |
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