🔴 Laravel Intermediate

What are Eloquent Relationships in Laravel?

Answer

Eloquent provides several relationship types for defining how models relate to each other. One-to-One: hasOne() / belongsTo(). One-to-Many: hasMany() / belongsTo(). Many-to-Many: belongsToMany() — requires a pivot table. Has Many Through: hasManyThrough() (access distant relations via an intermediate model). Polymorphic: morphTo() / morphMany() — a model belongs to multiple types. Access relations as properties (lazy loaded): $user->posts. Or as methods for chaining: $user->posts()->where("published", true)->get(). Each relationship method returns a query builder, enabling further constraints. Define foreign keys explicitly: hasMany(Post::class, "author_id", "id").