Relationships
| HasMany | |
| BelongsTo | |
| Eager loading | |
| Save related |
HasMany
A post owns many comments, which is a one-to-many link. The method name becomes the property you read, so fetching a post and its comments reads naturally.
The return type tells readers and tools what the method gives back. The related class is named, never spelled out with keys.
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\HasMany; class Post extends Model { public function comments(): HasMany { return $this->hasMany(Comment::class); } }
BelongsTo
The other side of the link is a comment that belongs to one post. BelongsTo is the mirror image of HasMany, read from the child up to the parent.
namespace App\Models; use Illuminate\Database\Eloquent\Model; use Illuminate\Database\Eloquent\Relations\BelongsTo; class Comment extends Model { public function post(): BelongsTo { return $this->belongsTo(Post::class); } }
Eager loading
Reading comments inside a loop can fire one query per post, which slows pages down fast. The with method preloads the relation in a single extra query.
Eager load every relation the page prints. Lazy loading stays fine for single models outside loops.
$posts = Post::with("comments")->get(); foreach ($posts as $post) { echo count($post->comments); }
Save related
New children can be created through the relation itself. Laravel fills the foreign key from the parent, so you never set it by hand.
$post = Post::find(1); $post->comments()->create(["body" => "Nice post!"]);
Next: Query builder
Article author: Arthur Isaev