In Laravel 5.1 I can see that table column relationships can be set-up in 2 ways:
1) Defining Foreign Keys in the Migration table.
2) De
Both go hand in hand. One is in-complete without the other one. If you want your relations to work properly, you need to define both of these things.
If you have just defined the foreign key in a migration file, the relation would work just in case you write a raw query. It won't work on your models since, you haven't written anything about relations in your models.
So, as soon as you write hasMany
in one of your models, and corresponding function in the other model, only then your models know about each other, and then you can successfully query things through your model as well as in your database.
Also note that if you have properly defined relations through hasMany
and belongsTo
in your models, but haven't provided foreign key in the table of the model who belongsTo
other table, your relations won't work.
In short, both are equally compulsory.
Eloquent assumes the foreign key of the relationship based on the model name. In this case, the App
model is automatically assumed to have an app_id
foreign key, so in your migrations you do not need to specify:
$table->foreign('app_id')
->references('id')
->on('apps')
->onDelete('cascade');
Documentation