Skip to content

Instantly share code, notes, and snippets.

@whoisryosuke
Last active March 21, 2022 13:17
Show Gist options
  • Save whoisryosuke/3c44285d965396279c5cdfc369992e8e to your computer and use it in GitHub Desktop.
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
<?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']),
]);
}
?>
@valdineireis
Copy link

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;

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment