I need to add a field on a table in my database, but the problem is that my app is already live and I have some data.
I want to add the 'slug' field inside 'users' table, and even tho I use the add migration, the 'slug' in my already existing users will be empty, how can I solve this avoiding to manually go in my db and fill out the slugs of my existing users
You will need to add the slug. But set the new migration to add a new column with default slug = ''. Then in the same migration set the slug on all existing users
Now I need to add a slug field, which can't be null.
I am going to create the 'add' migration adding the field, but how can I popolate it on the already existing users?
In this case like this
USER TABLE
name last_name slug
Jhon Doe john-doe
Ambra Lauren ambra-lauren
@Kris01 you need to allow it to be null or have a default. No way around it. After it has been created and users are updated, you can remove nullable/default. Think of it as a 3 step process.
public static function boot(): void
{
parent::boot();
self::creating(function ($model) {
// here you can decide what unique field will be used as slug, for ex. email
$model->slug = Str::slug($model->email);
});
self::updating(function ($model) {
if (!$model->isDirty('email')) {
$model->slug = Str::slug($model->email);
}
});
}
public function getRouteKeyName(): string
{
return 'slug';
}
Create new migration to update table:
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->string('slug')->unique();
});
}
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropColumn('slug');
});
}