DoeJohn
105
13
Laravel

Migrations: When to use index()?

Posted 8 months ago by DoeJohn

Should I addindex() for every field? Or just use it on foreign keys? Or?

For example, here's one migration:


    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->increments('id');

            $table->unsignedInteger('user_id');
            $table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');

            $table->unsignedInteger('category_id');
            $table->foreign('category_id')->references('id')->on('categories')->onDelete('cascade');
         
            $table->string('title');
            $table->string('slug')->nullable();
            $table->string('image')->nullable();
            $table->text('body');
            $table->text('excerpt')->nullable();

            $table->boolean('approved')->default(0);

            $table->timestamps();

            $table->unique(['category_id', 'slug']);
        });
    }

Which fields in this migration should be indexed? For example, I always add them on foreign keys:

$table->index('user_id');
$table->index('category_id');

Is this wrong (to always use index() on foreign keys)?

Would you index some other fields in this migration? If yes, which one?

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.