Laravel
Beginner
1 min read
Eloquent Relationships: hasMany, belongsTo, belongsToMany
Example
<?php
// Defining relationships in models
// app/Models/User.php
class User extends Model
{
// One user has many posts
public function posts()
{
return $this->hasMany(Post::class);
}
// One user has one profile
public function profile()
{
return $this->hasOne(Profile::class);
}
}
// app/Models/Post.php
class Post extends Model
{
// Each post belongs to a user
public function user()
{
return $this->belongsTo(User::class);
}
// Post belongs to many tags (pivot: post_tag)
public function tags()
{
return $this->belongsToMany(Tag::class)
->withPivot('order')
->withTimestamps();
}
}
// Usage in a controller:
// Eager load to avoid N+1
$posts = Post::with(['user', 'tags'])->published()->paginate(10);
// Attach/sync many-to-many
$post->tags()->sync([1, 2, 3]);
// Access pivot data
foreach ($post->tags as $tag) {
echo $tag->pivot->order;
}
Related Resources
Laravel Reference
Complete tag & property list
Laravel How-To Guides
Step-by-step practical guides
Laravel Exercises
Practice what you've learned
More in Laravel