Skip to content

Instantly share code, notes, and snippets.

@guiassemany
Created December 28, 2016 12:11
Show Gist options
  • Save guiassemany/6d37cabac8c28603952166518ea6a02b to your computer and use it in GitHub Desktop.
Save guiassemany/6d37cabac8c28603952166518ea6a02b to your computer and use it in GitHub Desktop.
Laravel model relations

One-to-one relationship:

You, as a User, can have one (hasOne) Profile. And of course the inverse also applies. Profile (belongsTo) a User. A user can't have more than one profile and a profile can't belong to multiple users.

One-to-many relationship:

You as a User, can have many (hasMany) Task(s). The inverse would be Task(s) (belongsTo) a User. So that means that a user can have/create many tasks, but each task only belongs to one user.

Many-to-many relationship:

You as a User can belong to many (belongsToMany) (i.e. forum) Group(s). The inverse would be that a Group can also belong to many (belongsToMany) User(s). That means that a user can join as many groups as he wants, and of course a single group can have unlimited users inside.

One other thing that is pretty good to know is that when you use belongsTo and belongsToMany you're telling Laravel that this table holds the foreign key that connects it to the other table. And of course hasOne and hasMany is telling Laravel that this table does not have the foreign key

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment