Search code examples
phplaravellaravel-8database-migrationlaravel-migrations

Creating a nickname from other columns by migration, laravel 8


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?


Solution

  • 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))";