X3R0
X3R0

Reputation: 6334

Max value limit for Laravel integer value DB record column

How would I, if possible, create an integer column in my database with a max limit.

Example:

I would like to do this in the database layer and not in my application layer.

So what would I put in my database migration file?

Example migration file:

class CreateUsersTable extends Migration
{
    public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->rememberToken();
            $table->timestamps();
        });
    }

    public function down()
    {
        Schema::dropIfExists('users');
    }
}

Upvotes: 2

Views: 3442

Answers (2)

cetver
cetver

Reputation: 11829

Column value limitation can be done via check constraint

Blueprint does not support it.

You need to run raw sql query

public function up()
{
    // table creation
    DB::statement('
        ALTER TABLE users 
        ADD CONSTRAINT users_x_check CHECK (x > 0 AND x <= 30)
    ');
}

Upvotes: 2

X3R0
X3R0

Reputation: 6334

SQL Limit min and max value in database, no clue if laravel supports check constraints. But you can create the table by hand. - @DefinitelynotRafal

Upvotes: 0

Related Questions