A “hidden” way to drop foreign keys in migrations

If we add a foreign key column in our migration file in function up(), we need to make sure that foreign key would be dropped in down() function, right? The thing is that you need to remember longer foreign key name to drop it by name. What official Laravel documentation doesn’t say is that there’s a more convenient way.

Let’s take a look at official Laravel documentation and what it says about foreign keys.

0215_laraveldaily_foreign_key

As you can see, we are dropping foreign key with dropForeign() function and parameter which has this format: [table]_[column]_foreign. But there is another way to drop foreign key – just by the name of the field, you just have to put it as array parameter.

So instead of

$table->dropForeign('posts_user_id_foreign');

We can just use this:

$table->dropForeign(['user_id']);

So, not everything is in the official documentation, sometimes dig deeper!

Like our articles?
Check out our Laravel online courses!

4 COMMENTS

  1. Good one 🙂 Always easier to just use foreign key name which you can easily look up at your migration file, instead of needing to provide table name and “foreign” string at the end as well.

LEAVE A REPLY

Please enter your comment!
Please enter your name here