Tutorials

A Practical Guide to Eloquent Relationships

belongsTo, hasMany, belongsToMany — when to use each, with real examples.

S
Sample Author

· 1 min read · 3,867 views

Laravel's Eloquent is one of the best ORMs in any language. But relationships trip up newcomers more than anything else.

hasOne vs belongsTo

The model that has the foreign key uses belongsTo.

hasMany

For one-to-many. A User hasMany Posts.

belongsToMany

For many-to-many through a pivot. Posts belongsToMany Tags.

The big tip: name your foreign keys consistently

Stick to {model}_id and Eloquent does most of the work for you.

About the author

S
Sample Author

Curious about the craft of building things on the web.

Writes about tech, life, and everything in between.

View profile

Related posts

Comments are closed for this post.

Reading

Preferences

Your preferences are saved on this device.