Laravel BigIncrements

Ariel Mejia Dev
Ariel Mejia Dev
Published in
2 min readApr 19, 2019

Some weeks ago I had a migration that did not run so I wrote this for everyone that is searching for BigIncrements solution, it´s really easy but maybe some example and context will help you.

In Laravel 5.8 the default auth artisan command provide us with a migration with “Users” table and bigIncrements field as ID, it creates a column with a big integer type field, instead of integer type and… Why it´s important to post about it ?

If you try to use the “Users” id as foreign key it will throws and error at the time to create a migration, because maybe you will try something like this:

Schema::create('authors', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});

This code will fail because “user_id” will be referenced as integer type but in “Users” table id field type is a big integer, so the length it´s different and all it´s going to crash! So what´s the best solution?

At this point maybe you will need the id field from “Users” table as BigIncrements to use the easiest way to avoid that all crashes, it´s simple just reference “user_id” as “BigInteger” like this:

Schema::create('authors', function (Blueprint $table) {
$table->bigIncrements('id');
$table->bigInteger('user_id')->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});

With this little change you are going to have the same type in “Users” and “Authors” table, so the migration will work fine.

That´s all folks, happy coding!

--

--

Ariel Mejia Dev
Ariel Mejia Dev

Fullstack Web/Mobile Developer and Laravel enthusiast.