Define hasMany, belongsTo, belongsToMany relationships and prevent N+1 with eager loading.
Eloquent Relationships
// One-to-Many
class User extends Model {
public function posts(): HasMany {
return $this->hasMany(Post::class);
}
}
class Post extends Model {
public function user(): BelongsTo {
return $this->belongsTo(User::class);
}
}
// Many-to-Many
class Post extends Model {
public function tags(): BelongsToMany {
return $this->belongsToMany(Tag::class)->withTimestamps();
}
}
// Has-Many-Through
class Country extends Model {
public function posts(): HasManyThrough {
return $this->hasManyThrough(Post::class, User::class);
}
}
// Eager loading (prevent N+1)
$posts = Post::with(["user", "tags", "comments.user"])->get();
// Attach / detach / sync (many-to-many)
$post->tags()->attach([1, 2, 3]);
$post->tags()->sync([2, 4]); // replace all