0
votes

I am a newbie when it comes to Laravel. I have been searching for ways to define my foreign keys, instead of defining them in the migrations. I have been asking around and googeling a lot and everyone says that you can do it in different ways. Some people say to just do it in the migrations and some people say it is possible to JUST define the foreign keys via the eloquent models.

Now my question is. Which way is the most effective and optimal way for me to have relations between my different laravel tables. Foreign keys via migrations, or are there any other good ways to do it? Like I said I am confused due to all the different answers. I have of course checked Laravel 4.2's documentation!

1

1 Answers

2
votes

A foreign key is part of your database schema and should ultimately be part of your migrations. When you create a foreign key in the database it keeps continuity throughout as foreign keys must be valid and exist in order for rows to be inserted.

I'm not sure how you would go about defining foreign keys in eloquent. You can tell eloquent what your foreign keys are and it will use those for querying relations, but this isn't creating a foreign key in the database. (If you don't define them laravel assumes a certain naming standard is used for the column names)

What is you reasoning behind not wanting to define them in the migrations?

By all means you don't have to define foreign keys in your database, eloquent relations will work just fine without them, but for better database storage, data continuity and performance you should define them