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?
CodePudding user response:
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))";
CodePudding user response:
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