Category : #laravel
Tags : #laravel, #database and migration
You may check for the existence of a table column in the Laravel application. Laravel provides Schema::hasColumn()
method to check whether a column exists in a table or not. In this tutorial, I will show how to check whether a column exists or not in a table in Laravel application.
It is good practice to check if a column exists in the Laravel table and then add a new column to the table. Let's see the example code of how to check if a column exists in laravel:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('products', function (Blueprint $table) {
if (Schema::hasColumn('products', 'price')) {
// The "products" table exists and has a "price" column...
}
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('products');
}
};
Read also: Laravel Refresh Database And Seed Together Example
Conclusion
I have tried to discuss the clear concept of how to check if a column exists in laravel. Now we know how to check if a column exists in laravel. Hope this how to check if a column exists in laravel tutorial will help you.