Regarding Relationship Of DB Tables In Laravel

- 1 answer

Suppose we have many to one relationship between table A and table B. Now there are two possibilities to define this relation in Laravel.

  1. while creating migration I use the "References" Keyword. and the run the migration

  2. The other way is I use hasMany and belongsTo in model class corresponding to those tables and do not mention References and all in migration tables.

Can some one help me in understanding what approach I should follow. Or we need to have both the approach in our codebase to create relationships. Can some one throw some light on it. I am kind of confused. I am new to Laravel and learning these intricacies. thank you.



Actually, you should use both 1 and 2 to make Eloquent relations work. If you're using raw queries, you can use only 1, but the real power of Laravel is in Eloquent model relations.

Eloquent assumes the foreign key of the relationship based on the model name