How to update column attributes in Laravel in best ways?

A database column has many items for validation and updates. In the last tutorial, we discussed how to update table value/s. Here let’s see how we can update column attributes or data types in Laravel.

The change() method

You can use the change method to modify the type and attributes of existing columns. For example, if you want to increase the size of a string column. To see the function of the change method, let’s increase the size of the full_name column from 50 to 100. To implement this, we define a new state of the column and then call the change method as shown below.

Schema::table('users', function (Blueprint $table) {
    $table->string('full_name ', 100)->change();

This updates the column entry for the database schema. We use the Schema::table façade for this. The change method is called on the arguments passed to update column attribute for characters length.

However, the change() method won’t work on many column types. The following column types can not be “updated”: char, double, mediumInteger, enum, timestamp, tinyInteger, json, jsonb, ipAddress, macAddress, mediumIncrements, morphs, nullableMorphs, nullableTimestamps, softDeletes, timeTz, timestampTz, timestamps, timestampsTz, unsignedMediumInteger, unsignedTinyInteger, uuid. To modify a timestamp column type, you must register a Doctrine type.

We can also update column attributes to allow null values for that column. This is useful when we don’t need to enter value for a field in a specific record but want to avoid errors for null value entry.

Schema::table('users', function (Blueprint $table) {
    $table->string('full_name', 100)->nullable()->change();

This enables us to insert or update a record and leave the full_name field empty without any database errors.

Leave a Comment