Laravel How to Add Enum Column Example

Sovary October 9, 2022 363
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

Founder of CamboTutorial.com, I am happy to share my knowledge related to programming that can help other people. I love write tutorial related to PHP, Laravel, Python, Java, Android Developement, all published post are make simple and easy to understand for beginner. Follow him