Intermediate LevelLaravel
How do Eloquent Relationships (hasMany, belongsTo, belongsToMany) work?
❓ Interview Prompt: Explain One-to-Many (hasMany/belongsTo), Many-to-Many (belongsToMany) pivot tables, withPivot(), and relationship query methods.
Eloquent relationships link database tables through intuitive model methods:
1. One-to-Many ('hasMany' / 'belongsTo'):
User model 'hasMany(Post::class)'; Post model 'belongsTo(User::class)'.
2. Many-to-Many ('belongsToMany'):
Users and Roles linked via pivot table ('role_user'). Use '->withPivot("expires_at")' to retrieve extra pivot table columns!
Code Implementation Example
php
<?php
namespace AppModels;
use IlluminateDatabaseEloquentModel;
use IlluminateDatabaseEloquentRelationsBelongsToMany;
class User extends Model
{
public function roles(): BelongsToMany {
return $this->belongsToMany(Role::class)
->withPivot('assigned_at')
->withTimestamps();
}
}💡Many-to-Many Eloquent relationship with custom pivot columns.
🎯 Interview Key Takeaway
Define Eloquent relationships (hasMany, belongsToMany) and use withPivot() to access extra pivot table fields.
#Relationships#Eloquent#Pivot Table#Intermediate
Back to all Laravel Questions→