Abrar Jahin Abrar Jahin - 1 year ago 207
MySQL Question

Laravel Migration - Adding Check Constraints In Table

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

PositionID INT,
Salary decimal(9,2)
CHECK (Salary < 150000.00)

What I have done is-

Schema::create('Payroll', function (Blueprint $table)
$table->integer('PositionID ');

But I can't create this-

CHECK (Salary < 150000.00)

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download