I’m creating a website with Laravel for the first time. I checked relationships documentation today and it seems that Laravel just uses simple SQL queries.
class User extends Eloquent {
public function phone()
{
return $this->hasOne('Phone');
}
}
$phone = User::find(1)->phone;
And it’s basically a select * from phones where user_id = 1 query. So the question is, should I use foreign keys anyway in my database to create relationships?
1
Foreign keys in your database enables data integrity, as you can’t delete a parent row if there is a child row in another table.
While you can rely on the framework to handle data for you, the framework will not enable data integrity and you will eventually end up with orphan rows in your database.
So, my advice is: design the database properly in order to preserve data.
1
The data belongs to the organization, not the application. While right now you’re using Laravel exclusively, in the future there might be several applications interacting with the database.
I’m currently working on an app that started in FoxPro, migrated to ASP classic, and was partially upgraded to ASP.NET. There are at least three applications interacting with the data and we’re working on integrating with more. Our database doesn’t use foreign keys, although it does sort of use triggers to emulate them, and I really wish it did.
2
Using the exact same words from @JeffO:
Isn’t user_id a foreign key?
I think the problem is not necessarily setting a foreign key or not. The problem is how much do you need to depend on the database features.
In Laravel you will set your foreign keys while adding your migrations.
But if you for any reason/error have a user having direct access to the database or using PHP features without the framework or whatever other issue the might not only rely on the framework, it is best practice to add foreign keys to your database.
Finally, I already worked on projects where they decided not to have foreign keys and rely only on the frameworks validations for maintenance reasons.