Make Proper Foreign Key in Laravel Migration with Constrained

Make Proper Foreign Key in Laravel Migration with Constrained

In this simple article I will show you how to create proper foreign key in laravel migration with constrained (e.g. delete) etc.

Well this will help you if you will delete the record in DB their correspondence referenced record will be automatically deleted as per Cascade rule DMBS. With this way you can create your migration code more flexible and readable likewise.

We use this syntax previously for making foreign id in tables. We can create with this way but the issue is that in some cases it does not delete the referenced record from table. And this situation create a problem in our system that the parent record is deleted but its foreign record is exist with their ID. So, this case is not useful.

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

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

?But!!!!!!!

Now we will create our foreign key with this way.

$table->foreignId('user_id')
->index()
->constrained()
->onDelete('cascade');        

How simple is that? Yes! This will definitely delete the its foreign referenced record from table as well.

Awesome.


Abdullah Ayman

Full stack web developer | Django | Laravel | React.js | NestJS | AWS | Hate: cryptocurrency trading

1 年

"We can create with this way but the issue is that in some cases it does not delete the referenced record from table."-- I never faced it. are you sure? If so, why is that?

回复
Samuel Atuahene

Software Engineer | Web Designer | IT Support Specialist | Motion Graphics Designer

1 年

How does it know it references the users table

回复

要查看或添加评论,请登录

社区洞察

其他会员也浏览了