Laravel Migration - Adding Check Constraints In Table

Abrar Jahin picture Abrar Jahin · Jul 6, 2016 · Viewed 8.6k times · Source

I want to create a table in Laravel Migration like this-

CREATE TABLE Payroll
(
 ID int PRIMARY KEY, 
 PositionID INT,
 Salary decimal(9,2) 
 CHECK (Salary < 150000.00)
);

What I have done is-

Schema::create('Payroll', function (Blueprint $table)
{
    $table->increments('id');
    $table->integer('PositionID ');
    $table->decimal('Salary',9,2);
    //$table->timestamps();
});

But I can't create this-

 CHECK (Salary < 150000.00)

Can anyone please tell, how to implement this CHECK constraints in Laravel Migration ?

Answer

Michael picture Michael · Aug 25, 2016

Adding constraints is not supported by the Blueprint class (at least as of Laravel 5.3), however it is possible to add constraints to your tables directly from your migrations, by using database statements.

In your migration file,

public function up ()
{
    Schema::create('payroll', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('position_id');
        $table->decimal('salary',9,2);
    });

    // Add the constraint
    DB::statement('ALTER TABLE payroll ADD CONSTRAINT chk_salary_amount CHECK (salary < 150000.00);');
}