How to update column attributes in Laravel in best ways?

A database column has many items for validation and updates. In the previous tutorial, we discussed how to update table value/s. Let’s learn here on how to update column attributes or data types in Laravel.

The change() method

The change method helps 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 may not won’t work on many column types. There are many column types that cannot be updated using the change method, like 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.