LARAVEL

Laravel Eloquent Relationships

February 20, 2024 16 min read

Introduction

Eloquent ORM provides powerful relationship handling. Understanding relationships is key to building efficient Laravel applications.

One-to-One Relationship

// User model has one Phone
class User extends Model
{
    public function phone()
    {
        return $this->hasOne(Phone::class);
    }
}

// Phone model belongs to User
class Phone extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

// Usage
$phone = $user->phone;
$user = $phone->user;

One-to-Many Relationship

// Post has many Comments
class Post extends Model
{
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

// Comment belongs to Post
class Comment extends Model
{
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

// Usage
$comments = $post->comments;
$post = $comment->post;

Many-to-Many Relationship

// User has many Roles (via role_user table)
class User extends Model
{
    public function roles()
    {
        return $this->belongsToMany(Role::class);
    }
}

class Role extends Model
{
    public function users()
    {
        return $this->belongsToMany(User::class);
    }
}

// Usage
$roles = $user->roles;
$users = $role->users;

// Attach/Detach
$user->roles()->attach($roleId);
$user->roles()->detach($roleId);
$user->roles()->sync([1, 2, 3]);

Polymorphic Relationships

// Comment can belong to Post or Video
class Comment extends Model
{
    public function commentable()
    {
        return $this->morphTo();
    }
}

class Post extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

class Video extends Model
{
    public function comments()
    {
        return $this->morphMany(Comment::class, 'commentable');
    }
}

// Usage
$post->comments;
$video->comments;
$comment->commentable;

Summary

Eloquent relationships provide a powerful way to work with related data. Master these relationships to build efficient Laravel applications.

For more Laravel tutorials, see Advanced Eloquent.