Append a incrementing number to a slug username Im using Laravel 5.4 and I'm using a slug to look-up users in database. 

Im adding first_name and last_name to the slug, and if there is a user with the same name, appending a number (increment it if there is more than one with same name) to the end ex John.doe.3.

This is what I have in RegisterController.php

protected function create(array $data)
    {
        // Set the may be name
        $maybe_slug = strtolower($data['first_name'] . '.' . $data['last_name']);

        // Check if there is another one in the DB with the same name
        $user = User::where('slug', 'like', $maybe_slug . '%')-&gt;orderBy('created_at', 'desc')-&gt;first();

        if($user){
            $split_user_name = explode('.', $user-&gt;slug);
            $number = isset($split_user_name[2]) ? $split_user_name[2] : null;
            if(isset($number)){
                $slug = $maybe_slug . '.' . ($number + 1);
            }elseif($user-&gt;slug == $maybe_slug){
                $slug = $maybe_slug . '.2';
            }
        }else{
                $slug = $maybe_slug;
        }
        return User::create([
            'first_name' =&gt; $data['first_name'],
            'last_name' =&gt; $data['last_name'],
            'slug' =&gt; $slug,
            'email' =&gt; $data['email'],
            'password' =&gt; bcrypt($data['password']),
        ]);
    }


This is how RegisterController looks like un-edited (GitHub)

Can I do this in a better way?
Searching for the slug duplicate in the database can be done in a more fast and straightforward way, by using = operator instead of like, and not using orderBy;
To be on the safe side, it's worth to make searches in a loop, incrementing the $next on each step;


So, it might look like this:

protected function create(array $data)
{
    $slug = $maybe_slug = strtolower($data['first_name'] . '.' . $data['last_name']);
    $next = 2;

    while (User::where('slug', '=', $slug)-&gt;first()) {
        $slug = "{$maybe_slug}.{$next}";
        $next++;
    }

    return User::create([
                'first_name' =&gt; $data['first_name'],
                'last_name' =&gt; $data['last_name'],
                'slug' =&gt; $slug,
                'email' =&gt; $data['email'],
                'password' =&gt; bcrypt($data['password']),
    ]);
}