Eloquent: Creating table with auto-incrementing ID

Updated: January 16, 2024 By: Guest Contributor Post a comment

Introduction

Laravel’s Eloquent ORM provides an elegant and simple way to interact with your database. A common requirement when designing databases is to have a unique identifier for each row in a table, commonly achieved with an auto-incrementing ID. In this tutorial, we’re going to explore how to create tables that utilize an auto-incrementing ID using Eloquent’s migrations and how this can be utilized effectively within your Laravel applications.

Prerequisites

  • Basic knowledge of Laravel framework.
  • A Laravel application set up on your local development environment.
  • Familiarity with Eloquent ORM and its usage.
  • Understanding of database migrations in Laravel.

Creating a New Migration

To start, we need to create a new migration file that defines the structure of our table. We can do this with the Laravel Artisan command:

php artisan make:migration create_posts_table

This will create a new migration file within the database/migrations directory. Open this file, and you will find a boilerplate migration class ready for your customization.

Defining the Schema with Auto-incrementing ID

In the up method of your migration, you can define the table’s columns and data types. Here’s how to define a simple ‘posts’ table with an auto-incrementing ID:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('title');
        $table->text('content');
        $table->timestamps();
    });
}

The bigIncrements method creates an BIGINT equivalent column that is auto-incrementing and intended to be used as a primary key. If you want a regular INT, use the increments method instead. Both will be set as primary keys by default.

Running the Migration

Save the migration file and run the following command to apply your migration to the database:

php artisan migrate

Your ‘posts’ table is now created with an auto-incrementing ID!

Advanced Usage

Customizing the Primary Key

If you want to customize the primary key name and auto-incrementer, you can do so by using the increments or bigIncrements methods along with other Fluent methods:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->increments('custom_id');
        // Other columns...
    });
}

You can then specify which column to use as the primary key within your Eloquent model:

class Post extends Model
{
    protected $primaryKey = 'custom_id';

    public $incrementing = true;

    // Rest of the class...
}

Non-Auto-Incrementing Primary Key

If, for any reason, your table’s primary key should not auto-increment, you will still need to tell Eloquent about your key:

class Post extends Model
{
    public $incrementing = false;

    // Rest of the class...
}

UUIDs as Primary Keys

You can also use UUIDs instead of numeric auto-incrementing IDs. Adjust the migration and model accordingly:

public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->uuid('id')->primary();
        // Other columns...
    });
}


public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->uuid('id');
        // Other columns...
    });
}

In your model, you would disable incrementing and also let Eloquent know your key’s type:

class Post extends Model
{
    public $incrementing = false;

    protected $keyType = 'string';

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            if (empty($model->{{$primaryKey}})) {
                $model->{{$primaryKey}} = Str::uuid();
            }
        });
    }

    // Rest of the class...
}

Note that you must ensure that UUIDs are generated for new models. The extending of the boot method as shown above is a common way to achieve this.

Conclusion

In this tutorial, we have learned how to create a database table with an auto-incrementing ID using Laravel’s Eloquent ORM. Starting with a basic migration, we’ve looked at various ways to customize auto-incrementing behavior, including the use of UUIDs. Eloquent’s flexibility allows developers to tailor their application’s data layer to precisely fit their needs.