sql - 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');

For me it's the same because foreign key is an index, am I right ?

2 Answers

  1. Leonard- Reply

    2019-11-14

    Reference to this question, it's good to index a foreign key, but database won't index it automatically.

    So 2 code blocks above are different.

    I think you can try to open your database schema and check for it.

  2. Leopold- Reply

    2019-11-14

    I found my answer:

    Some databases by default put indexes on all created foreign keys automatically.

    Eloquent only does a - create foreign key - command for and MySQL automatically adds the index.

    Thanks to Mittensoff from laracasts for the answer ;)

Leave a Reply

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

You can use these HTML tags and attributes <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>