How to check If Database Table Column Exists in Laravel Migration

In this short Laravel tutorial you will learn how to do a Laravel migration check to see if a column exists in a database table. By doing this migration check you can avoid a fatal error such as the following one while trying a migration against a MySQL table.

SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name...

Why to check if a column exists in Laravlel Migration?

Before executing the column changing command, for example, ALTER `table` ADD `column_name`  in MySQL, we may need to verify whether the column in question does not exist in the database table. We can do the same for DROP Column command as well.

How to check if a column exists

To do the column existence check, we are going to use the hasColumn method of Schema facade of Laravel. The Schema facade is used to perform table management actions in a database table.

In the migration file, use and modify the following example code to inside up() or down() methods, according to your requirements:

if ( !Schema::hasColumn('users', 'some_field_name') )
{
    Schema::table('users', function (Blueprint $table)
    {
        $table->string('some_field_name')->nullable();
    });
}

Conclusion

To sum up, we have learned how to implement a ‘column exists’ check in a Laravel migration. We can use the hasColumn method of the Schema facade or the Laravel framework to perform this check.

Leave a Reply