Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

lxg's avatar
Level 1

How do i add a colum to my database table without losing my Database Entrys

Hello,

I implemented a Laravel Application with a database. I have a table named cars with 150 entrys. i'd like to add a column named seats and set it to 5 for every car, and would change the cars with 9 seats to that number manually later. What would be the best way to add this column without deleting all my entrys?

Best regards Alex

0 likes
6 replies
bobbybouwmann's avatar

If you have a migration that adds one column with a default value, it won't delete the other entries in the database. One important thing is that you set a default value for that column or make it nullable! So your migration will look like this:

public function up()
{
    Schema::table('cars', function (Blueprint $table) {
        $table->integer('seats')->default(5);
    });
}

So you need to create a new migration using php artisan make:migration add_seats_cars_table to be clear! If you run php artisan migrate the column will be added without losing any data ;)

click's avatar

Why would you think that you need to delete all of your entries?

You can create a migration to add the column to your table and create a manual query to update all seats to 5.

Something like this would do the trick: Depending on your requirements you could set your amount of seats to default null (nullable, when you don't know) or to an integer like 5.

Schema::table('cars', function (Blueprint $table) {
  $table->integer('seats')->nullable()->after('some_other_field'); 
});

DB::query('UPDATE cars SET seats = 5 WHERE seats IS NULL');
lxg's avatar
Level 1

Nice, Thank you two, i will try this

bugsysha's avatar

@lxg please select the answer that helped you as correct one so that person gets the points they've earned and so others will easier see that the problem is solved and if anyone has the same issue they will know right away what helped you. Thanks.

1 like
bobbybouwmann's avatar

@click Some people update the initial migrations and therefore they lose all there data because they need to remigrate the whole database. Not everyone is known with this approach ;)

jlrdw's avatar

Backup your data (export it) prior to messing around with changes.

Please or to participate in this conversation.