Abrar Jahin Abrar Jahin - 5 months ago 74
MySQL Question

Laravel Migration - Adding Check Constraints In Table

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

This feature is not included in the Blueprint class, so you can't do that in your migration file.

But in your Payroll model, you can create a mutator:

class Payroll extends Model{

    public function setSalaryAttribute($value){
        $this->attributes['Salary'] = $value < 150000.00 ? $value : 150000.00;
    }

}

So when a payroll Salary attribute is created or updated, this method will be automatically triggered and will check that the new value doesn't exceed 150000.00

EDIT: You should take a look at the mutators documentation in Laravel Docs.