Mastering Eloquent Relationships
Laravel's Eloquent ORM provides a beautiful, simple ActiveRecord implementation for working with your database.
Defining Relationships
One-to-One
class User extends Model
{
public function profile()
{
return $this->hasOne(Profile::class);
}
}class Profile extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
One-to-Many
class User extends Model
{
public function posts()
{
return $this->hasMany(Post::class);
}
}class Post extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
Many-to-Many
class User extends Model
{
public function roles()
{
return $this->belongsToMany(Role::class)
->withPivot('assigned_at')
->withTimestamps();
}
}
Eager Loading
Prevent N+1 query problems with eager loading:
// Bad - N+1 queries
$users = User::all();
foreach ($users as $user) {
echo $user->profile->bio; // Query for each user
}// Good - Only 2 queries
$users = User::with('profile')->get();
foreach ($users as $user) {
echo $user->profile->bio;
}
// Nested eager loading
$users = User::with(['posts.comments', 'profile'])->get();
Query Scopes
class Post extends Model
{
public function scopePublished($query)
{
return $query->where('published_at', '<=', now());
} public function scopeByAuthor($query, $userId)
{
return $query->where('user_id', $userId);
}
}
// Usage
Post::published()->byAuthor(1)->get();