A Practical Guide to Eloquent Relationships
belongsTo, hasMany, belongsToMany — when to use each, with real examples.
· 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
Curious about the craft of building things on the web.
Writes about tech, life, and everything in between.
View profileRelated posts
Welcome to Blog of Post
A modern blog platform built on Laravel and Filament. Read about what makes it tick.
Why Filament Changed How I Build Admin Panels
I used to spend weeks on internal tools. Filament cut that to a single afternoon.
Comments are closed for this post.