Методы проверки наличия столбца в таблице в Laravel с примерами кода

Чтобы проверить, есть ли в таблице столбец в Laravel, вы можете использовать один из следующих методов:

Метод 1: построитель схем

use Illuminate\Support\Facades\Schema;
$tableName = 'your_table_name';
$columnName = 'your_column_name';
if (Schema::hasColumn($tableName, $columnName)) {
    // Column exists in the table
    // Your code here
} else {
    // Column does not exist in the table
    // Your code here
}

Метод 2: необработанный запрос к базе данных

use Illuminate\Support\Facades\DB;
$tableName = 'your_table_name';
$columnName = 'your_column_name';
$columnExists = DB::select("SHOW COLUMNS FROM $tableName LIKE '$columnName'");
if ($columnExists) {
    // Column exists in the table
    // Your code here
} else {
    // Column does not exist in the table
    // Your code here
}

Метод 3: Красноречивая модель

use App\Models\YourModel;
$columnName = 'your_column_name';
if (YourModel::whereNotNull($columnName)->exists()) {
    // Column exists in the table
    // Your code here
} else {
    // Column does not exist in the table
    // Your code here
}

Метод 4: файл миграции
Вы можете создать новый файл миграции и использовать метод hasColumnвнутри метода миграции up:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CheckColumnExists extends Migration
{
    /
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        $tableName = 'your_table_name';
        $columnName = 'your_column_name';
        if (!Schema::hasColumn($tableName, $columnName)) {
            Schema::table($tableName, function (Blueprint $table) use ($columnName) {
                $table->string($columnName);
            });
        }
    }
    /
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        $tableName = 'your_table_name';
        $columnName = 'your_column_name';
        if (Schema::hasColumn($tableName, $columnName)) {
            Schema::table($tableName, function (Blueprint $table) use ($columnName) {
                $table->dropColumn($columnName);
            });
        }
    }
}

После выполнения любого из этих методов вы можете выполнить желаемое действие в зависимости от того, существует столбец или нет.