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

murilo's avatar
Level 10

laravel migration, add a rule if status is draft is nullable if is completed , is not null

hello , I want to know if is able to do something in Laravel . I have a postgres database , and in postgres you can CHECK a filed on CREATE TABLE .

I wold like to make a laravel migration , and CHECK the status of a FIELD -

  • if the STATUS is DRAFT - TITLE field is NULLABLE ,
  • if the STATUS is ACTIVE - TITLE cant be NULLABLE .

so my migration wold be like this -

class Property extends Migration
{

    public function up()
    {
        Schema::create('property', function (Blueprint $table) {
            $table->bigIncrements('id');

           $table->enum('status',['draft','active'])->default('draft');
		   $table->string('title', 300)->nullableIf( 'status' ===   'draft');


I know that this function nullableIf , does not exists . was just to give an example . but I wold like to know if it is possible to do something like this . if the status if DRAFT , field - TITLE is NULLBLE .

0 likes
1 reply
LaryAI's avatar
LaryAI
AI
Best Answer
Level 58

In Laravel, you can't directly add conditional constraints like nullableIf in the migration file. However, you can achieve this using database-level constraints in PostgreSQL. You can add a CHECK constraint to enforce this rule.

Here's how you can modify your migration to include a CHECK constraint:

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\DB;

class Property extends Migration
{
    public function up()
    {
        Schema::create('property', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->enum('status', ['draft', 'active'])->default('draft');
            $table->string('title', 300)->nullable();
        });

        // Add the CHECK constraint
        DB::statement('ALTER TABLE property ADD CONSTRAINT check_title_status CHECK (
            (status = \'draft\' AND title IS NULL) OR
            (status = \'active\' AND title IS NOT NULL)
        )');
    }

    public function down()
    {
        Schema::dropIfExists('property');
    }
}

In this solution:

  1. We first create the property table with the status and title columns.
  2. After creating the table, we use a raw SQL statement to add a CHECK constraint to the table. This constraint ensures that if the status is draft, the title must be NULL, and if the status is active, the title must not be NULL.

This approach leverages PostgreSQL's ability to enforce complex constraints at the database level, ensuring data integrity according to your specified rules.

Please or to participate in this conversation.