2

since Eloquent supports relationships, would you recommend to additionally define foreign key constraints in the migrations? Why?

Thanks

alexandre
  • 286
  • 3
  • 17

3 Answers3

7

Eloquent supports relationships, but it doesn't enforce them - that has to be done in the database itself. Databases also have a habit of outliving code. What happens when you want to use this database with some other ORM in the future?

Defining foreign key constraints is generally considered "good design", regardless of how you end up consuming that database.

alexw
  • 8,468
  • 6
  • 54
  • 86
  • Thanks for your quick answer. I learned foreign key constraints also as good design, but got unsure if there could come trouble from using them together with eloquent. Now, I can be sure and use it. – alexandre Mar 16 '16 at 18:14
1

Sure i would recommend you additionally define foreign key constraints for only one reason.

Laravel does not support cascade delete out of the box. This makes handling of cascading deletion of deep related records a pain.

oseintow
  • 7,221
  • 3
  • 26
  • 31
  • Actually it only takes a single bootable trait to achieve this. Also its very much desirable to do this in eloquent where there are event based reactive changes bound with the models. – Umair Ahmed Sep 28 '22 at 06:17
0

It is indeed considered good design and I would recommend implementing them yourself in Eloquent using a BaseModel class and bootable traits for such.

Nowadays, Eloquent has robust reactive event based mechanisms which must be kept in the know of such constraints and updates to properly reflect them throughout the system.

Common use cases would be an ACL audit system, database recovery, cache sync or bindings update mechanisms etc.

Umair Ahmed
  • 2,420
  • 1
  • 21
  • 40