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:
- We first create the
propertytable with thestatusandtitlecolumns. - After creating the table, we use a raw SQL statement to add a
CHECKconstraint to the table. This constraint ensures that if thestatusisdraft, thetitlemust beNULL, and if thestatusisactive, thetitlemust not beNULL.
This approach leverages PostgreSQL's ability to enforce complex constraints at the database level, ensuring data integrity according to your specified rules.