Eloquent relationships make it easy to work with related database tables using expressive, readable PHP code.
// User has many Posts
class User extends Model
{
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
}
// Post belongs to User
class Post extends Model
{
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
// Usage
$posts = $user->posts; // Collection of posts
$author = $post->user; // Single User model
$user->posts()->create([...]); // Create a related post
class Post extends Model
{
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class);
}
}
// Usage
$post->tags()->attach($tagId);
$post->tags()->sync([$tagId1, $tagId2]);
$post->tags()->detach($tagId);
class User extends Model
{
public function profile(): HasOne
{
return $this->hasOne(Profile::class);
}
}
// Load posts with their author and tags in 2 queries total
$posts = Post::with(['user', 'tags'])->latest()->get();
// Conditional eager loading
$posts = Post::with(['comments' => fn ($q) => $q->latest()->limit(3)])->get();
// Lazy eager loading on an existing collection
$posts->load('user');