Last active
March 21, 2022 13:17
-
-
Save whoisryosuke/3c44285d965396279c5cdfc369992e8e to your computer and use it in GitHub Desktop.
Laravel: Check database for duplicate slugs and generate incrementing slug name (repeat-name-2, repeat-name-3). Found via: https://codereview.stackexchange.com/questions/162254/append-a-incrementing-number-to-a-slug-username
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 | |
protected function create(array $data) | |
{ | |
$slug = str_slug($data['first_name'] . '.' . $data['last_name']); | |
$next = 2; | |
// Loop until we can query for the slug and it returns false | |
while (User::where('slug', '=', $slug)->first()) { | |
$slug = $slug . '-' . $next; | |
$next++; | |
} | |
return User::create([ | |
'first_name' => $data['first_name'], | |
'last_name' => $data['last_name'], | |
'slug' => $slug, | |
'email' => $data['email'], | |
'password' => bcrypt($data['password']), | |
]); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi Ryosuke, in this example, you can use an auxiliary variable to get the expected result. :)
line 4:
$slug = $slugBase = str_slug($data['first_name'] . '.' . $data['last_name']);
line 9:
$slug = $slugBase . '-' . $next;