Laravel How to Add Enum Column Example

Sovary October 9, 2022 517
1 minute read

This short example we are going to show you how to add enum value in Laravel migration file. We will go though step by step how to insert new field with enum value in database. You can simply see how to add new column support enum type in migration file Laravel.

In various scenario value field in table need constant value, we don't want to accept other value beside those values. For example gender column should contain only two values which are female or male. This mean you can set as enum data type in MySQL database, so in Laravel we can add column or field table in migration file and below steps will help you to create or implement enum data type in Laravel migration file.

Laravel 9 How to Add Enum Column

Example #1 - Add Enum Data Type with Default Value

<?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('students', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('nationality');
            $table->enum('gender', ['Female','Male']);
            $table->enum('status', ['Married','Single'])->default('Single');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
};

Anyway we can set default value if there is no data entry to the enum value. Thanks for reading my article, hope this short tutorial would help you.

You might also like...

 

Laravel  PHP  Laravel 9 
Author

As the founder and passionate educator behind this platform, I’m dedicated to sharing practical knowledge in programming to help you grow. Whether you’re a beginner exploring Machine Learning, PHP, Laravel, Python, Java, or Android Development, you’ll find tutorials here that are simple, accessible, and easy to understand. My mission is to make learning enjoyable and effective for everyone. Dive in, start learning, and don’t forget to follow along for more tips and insights!. Follow him