Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Migration - Adding Check Constraints In Table

Tags:

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 ?

like image 508
Abrar Jahin Avatar asked Jul 06 '16 11:07

Abrar Jahin


People also ask

How does Laravel keep track of migrations?

Each migration file name contains a timestamp, which allows Laravel to determine the order of the migrations. If you would like to specify a custom output path for the generated migration, you may use the --path option when executing the make:migration command.


1 Answers

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);');
}
like image 158
Michael Avatar answered Nov 12 '22 05:11

Michael