Created
May 28, 2016 13:48
-
-
Save placidrod/1e71e573919993ebfa5a6043998cd92d to your computer and use it in GitHub Desktop.
Laravel Create Unique Slug in AppServiceProvider
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
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