Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

raphadko's avatar

Laravel Validation - Check if a column exists

I'm using laravel's awesome validation classes, but I need to know if a column exists in the table (not a row in a given column, the column itself)

Is there a quick/easy way to check this without having to write a custom validation rule? If not, how could I write a validation rule for that?

Thanks

0 likes
6 replies
tangoG's avatar
tangoG
Best Answer
Level 4

You can check a whether a column exists or not by

if(Schema::hasColumn('users', 'email')) ; //check whether users table has email column
{
 //your logic
}
23 likes
bgarrison25's avatar

This is the right answer but what about a migration file that adds multiple columns? We could wrap every dropColumn in a seperate Schema anonymous function. There is also a hasColumns that checks that every column exists. What if you want to check for partial existence?

scottzirkel's avatar

You could build an array of the names of the columns you want to drop, if they exist, then pass that through to dropColumn.

$columns = [];

if (Schema::hasColumn('users', 'email'));
{
    array_push($columns, 'email');
}

if (Schema::hasColumn('users', 'age'));
{
    array_push($columns, 'age');
}

if (count($columns)) {
    Schema::table('users', function (Blueprint $table) use ($columns) {
        $table->dropColumn($columns);
    });
}

*Edit: I know the original post is two years old at this point, but I still found the accepted answer helpful, and since there was a question asked just a month ago, I figure it's still relevant.

crossmar's avatar

@SCOTTZIRKEL - Why do you have semicolons at the end of your initial if statements ? That would seem to exclude the block.

Please or to participate in this conversation.