Modify Columns using Migration in Laravel

Laravel's migration changes lets you undo the latest or a set number of database changes.

This post is focused on laravel migration changes

Changing Column Datatype

php artisan make:migration change_datatype_in_product_backups_table


public function up(): void
{
     Schema::table('product', function (Blueprint $table) {
     $table->string('desc')->nullable()->change();
});
}
public function down(): void
{
     Schema::table('product', function (Blueprint $table) {
     $table->boolean('desc')->nullable()->change();
});
}

Rename Existing Column Name

php artisan make:migration rename_column_in_table

public function up()
{
      Schema::table('product', function (Blueprint $table) {
      $table->renameColumn('desc', 'description');
});
}
public function down()
{
    Schema::table('product', function (Blueprint $table) {
    $table->renameColumn('description', 'desc');
});
}


Modifying database indexes, including adding, renaming, or removing them


Make column nullable

php artisan make:migration change_col_to_nullable_in_prodcuct_table --table=product
public function up(){
   Schema::table('product', function (Blueprint $table) {
       $table->text('price')->nullable()->change();
   });
}

public function down(){
        Schema::table('product', function (Blueprint $table) {
       $table->text('price')->nullable(false)->change();
   });
}

Make column non nullabl

public function up(){
        Schema::table('product', function (Blueprint $table) {
        $table->type('price')->nullable(false)->change();
   });
}

public function down(){
        Schema::table('product', function ($table) {
        $table->type('price')->nullable()->change();
   });
}

In laravel 8, you just have to put this: "->nullable()"
$table->string('name')->nullable(); 

Change Column Length

public function up() {
     Schema::table(‘product’, function (Blueprint $table) {
        $table->string(‘name’, 80)->change();
    });
}

d

Author
Full Stack Developer

Deepak Talwar

Technical Architect & Full Stack Developer with 18+ years of Professional Experience in Microsoft Technologies & PHP Platform. Hands on experience with C#, VB, ASP.NET, ASP.NET MVC, ASP.NET Core, ASP.NET Web API, Linq, ADO.NET, Entity Framework, Entity Framework Core, Sql Server, MYSQL, NoSql, Javascript, Angular, jQuery, AWS, Azure, React, Angular, Laravel, Codeingiter, Serenity, VBA, Cloud Computing, Microservices, Design Patterns, Software Architecture, Web Design and Development.

Related Post