Skip to content

Instantly share code, notes, and snippets.

@placidrod
Created May 28, 2016 13:48
Show Gist options
  • Save placidrod/1e71e573919993ebfa5a6043998cd92d to your computer and use it in GitHub Desktop.
Save placidrod/1e71e573919993ebfa5a6043998cd92d to your computer and use it in GitHub Desktop.
Laravel Create Unique Slug in AppServiceProvider
public function boot()
{
Post::saving(function ($post) {
$title = $post->title;
$proposed_slug = strtolower(str_replace(' ', '-', $title));
$existing_slug = Post::where('slug', $proposed_slug)->where('id', '<>', $post->id)->first();
if(! $existing_slug) {
$post->slug = $proposed_slug;
} else {
$number_added_to_proposed_slug = 0;
do {
$number_added_to_proposed_slug += 1;
$numbered_proposed_slug = $proposed_slug . '-' . $number_added_to_proposed_slug;
$existing_slug = Post::where('slug', $numbered_proposed_slug)->Where('id', '<>', $post->id)->first();
} while ($existing_slug);
$post->slug = $numbered_proposed_slug;
}
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment