Ways to declare unsigned columns in the Laravel migrations

Laravel developers love the way it handles relationships between tables by just associating models with each other.

The column which defines the relationship between tables must be of unsigned type.

In this tutorial, we’ll see how we can declare columns as unsigned in different ways in Laravel.

You need to import Illuminate\Database\Schema namespace with use keyword.

Using unsignedInteger column types

  $table->unsignedInteger('user_id');

Using only integer column type

  $table->integer('user_id', false, true);

Using integer column type with unsigned column modifier

  $table->integer('user_id')->unsigned();

Example

use Illuminate\Database\Schema;

Schema::create('comments', function (Blueprint $table) {
  // Using `unsignedInteger` column types
  // For foreign key relationship with users table
  $table->unsignedInteger('created_by');

  // Using only `integer` column type
  // For foreign key relationship with posts table
  $table->integer('post_id', false, true);

  // Using `integer` column type with `unsigned` column modifier
  // For foreign key relationship with comments table
  $table->integer('reply_to_comment_id')->unsigned();
});

Few more column types

Column typeDescription
unsignedBigInteger('likes');UNSIGNED BIGINT equivalent column.
unsignedDecimal('amount', 8, 2);UNSIGNED DECIMAL equivalent column with a precision (total digits) and scale (decimal digits).
unsignedInteger('likes');UNSIGNED INTEGER equivalent column.
unsignedMediumInteger('likes');UNSIGNED MEDIUMINT equivalent column.
unsignedSmallInteger('likes');UNSIGNED SMALLINT equivalent column.
unsignedTinyInteger('likes');UNSIGNED TINYINT equivalent column.

For more, you can check the official documentation for migrations creating-columns page.

Happy coding

Avatar

A web geek, an industry experienced web developer & tutor/instructor residing in India 🇮🇳

Next
Previous

Related