Neabfi's avatar

Foreign key and index

Is there any difference between

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

and

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

When I create a foreign key without any index, I see in my database that the foreign key is an index. I don't know exactly what is eloquent's behavior. Is it really the same ?

0 likes
3 replies
Mittensoff's avatar
Level 3

Some databases (such is MySQL InnoDB which are probably using) by default put indexes on all created foreign keys automatically.

Eloquent only does a - create foreign key - command for you and MySQL automatically adds the index (ofc, when you don't write ->index()).

12 likes
Mohamed2209's avatar

@Mittensoff Can I tell MySQL not to create that index?

I have another composite index for this column, so the single index will not be used in search queries. It will only slow down updates.

Please or to participate in this conversation.