How to convert string to boolean in laravel migration?

by elise_daugherty , in category: PHP Frameworks , 5 months ago

How to convert string to boolean in laravel migration?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by lily , 5 months ago

@elise_daugherty 

To convert a string column to a boolean type in a Laravel migration, you can use the ->boolean() method when defining the column in the Schema class. Here's an example of how to do this in a migration file:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
use IlluminateDatabaseSchemaBlueprint;
use IlluminateDatabaseMigrationsMigration;

class UpdateUserTable extends Migration
{
    public function up()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->boolean('is_active')->default(false)->change();
        });
    }

    public function down()
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('is_active')->default('0')->change();
        });
    }
}


In this example, we're converting the is_active column from a string type to a boolean type in the users table. The ->boolean() method is used to define the column as a boolean type, and the ->change() method is used to perform the conversion. You can also specify a default value for the boolean column using the default() method.


After making the migration changes, you can run php artisan migrate to apply the migration and convert the string column to a boolean type in the database.