2

I have a table with users, which includes fields for "first name" and "last name" and I need to create a "nick" field during migration and fill them in by creating a string of lowercase letters from the firstname and lastname without spaces.

Unfortunately, I can't find a way to auto-complete this column with other columns.

Can anyone help me?

clover
  • 35
  • 5
  • *"the firstname and lastname **without spaces.**"* - Please be aware that both first and last names _can_ contain spaces. If you're generating the nickname from existing first and last name values, you'll need to handle that possibility – Tim Lewis May 25 '22 at 15:17

2 Answers2

3

You need to use a raw query to update the column after it's created that will grab the two columns, concatenate them, and convert them to lowercase.

  Schema::table('users', function(Blueprint $table) {
       $table->string('nick')->nullable();
  });

  DB::query("UPDATE users SET nick = LOWER(CONCAT(first_name, last_name))";
aynber
  • 22,380
  • 8
  • 50
  • 63
0

If the nickname should not be unique, you can also listen to the created event inside User model like this:

class User extends Model
{
  /**
  * The "booted" method of the model.
  *
  * @return void
  */
  protected static function booted()
  {
    static::created(function ($user) {
        $user->nickname = Str::lower($user->first_name . $user->last_name);
        $user->save();
    });
  }
}

More on events here: https://laravel.com/docs/8.x/eloquent#events-using-closures

Sergiu Svet
  • 101
  • 1
  • 2
  • 8