auto increments laravel migrations

How to set auto-increment start in Laravel migrations?

Laravel has a great database migration mechanism, but there are some things missing there. For example, what if you want your IDs start with some number, like 140001, 140002 etc?

By default, we have a function increments() to set auto_increment:

Now, there’s no method or function to do something like this:

So we have two options here – both involve interacting with database after we create the initial schema.

Option 1. Raw DB Statement

After Schema::create(), just launch a raw SQL statement to change auto_increment value:

Option 2. Insert and delete record

Another feature of database is that after deleting the record, default auto_increment value still stays the same and continues from the latest number. So you can do this:

So, which method do you prefer? Have you done something like that in your projects?

Update 2018-01-01. Our reader Gabriel Caruso tried to commit a pull request to the core framework for this.

laravel auto_increment start pull request

But Taylor rejected it with short answer “No plans to add right now”.

laravel taylor pull request

Liked the article? Maybe you need help with your Laravel project?
Check out my Upwork profile and hire me!

5 thoughts on “How to set auto-increment start in Laravel migrations?

  1. hi, is that possible to use such method in seeder? there will be most useful.

    example we say country X id =1 and then in state seeder we say state X under id 1 in countries table.

  2. I would stick with the first one. Although you’re directly interacting with the database your purpose is clear immediatly; there is no second guessing what you want to achieve. With the second option the outcome is sort of a side effect of inserting and deleting an eloquent entity.

    Third option; a PR for this functionality in laravel’s scheme creator ? 😉

    1. Yeah, agree first approach is more understandable. And with third approach it is possible but then we would need to take into account all supported databases (it’s not only MySQL) so it’s a little more complicated than it seems on the surface.

Leave a Reply

Your email address will not be published. Required fields are marked *