DEV Community

Nwanguma Victor
Nwanguma Victor

Posted on • Updated on

Adding, Renaming, & Removing Columns from Existing Tables Using Tinker in Laravel

Enter Into Tinker Environment

On the CLI run artisan command to enter into tinker environment

php artisan tinker
Enter fullscreen mode Exit fullscreen mode

Adding Columns

Run the suggested code directly from Tinker.

Schema::table('<YOUR TABLE>', function ($table) {
    $table->string('name')->nullable()
        ->after('<DESIRED COLUMN>'); // add after desired column
});
Enter fullscreen mode Exit fullscreen mode

Renaming Columns

Run the suggested code directly from Tinker.

Schema::table('<YOUR TABLE>', function ($table) {
    $table->renameColumn('<FROM>', '<TO>');
});
Enter fullscreen mode Exit fullscreen mode

Removing Columns

Run the suggested code directly from Tinker.

Schema::table('<YOUR TABLE>', function ($table) {
   $table->dropColumn('<DESIRED COLUMN>');
});
Enter fullscreen mode Exit fullscreen mode

You may drop multiple columns from a table by passing an array of column names to the dropColumn method:

Schema::table('<YOUR TABLE>', function ($table) {
   $table->dropColumn(['<DESIRED COLUMN>', '<DESIRED COLUMN 1>']);
});
Enter fullscreen mode Exit fullscreen mode

Note

You can also use arrow functions

Schema::table('<YOUR TABLE>', fn($t)=> $t->string('<DESIRED COLUMN>')->nullable());
Enter fullscreen mode Exit fullscreen mode

Top comments (0)