Sling Academy
Home/PHP/Working with one-to-many relationships in Eloquent (with examples)

Working with one-to-many relationships in Eloquent (with examples)

Last updated: January 17, 2024

Introduction

When developing applications with Laravel, understanding Eloquent relationships is fundamental for the proper management of database records. One of the most common types of relationships in database design is the one-to-many relationship. This guide will walk through the implementation of such relationships using Eloquent ORM with practical examples to help you understand and apply these concepts in your own Laravel projects.

What is a One-to-Many Relationship?

A one-to-many relationship occurs when a record in one table is related to multiple records in another table. For instance, a blog post (‘one’) might have many comments (‘many’). Eloquent makes managing these relationships easy and intuitive.

Defining One-to-Many Relationships

We’ll start by setting up our models and migration files. Assume we’re dealing with a blog, where a Post model has many Comment models.

// app/Models/Post.php
class Post extends Model {
    public function comments() {
        return $this->hasMany(Comment::class);
    }
}

// app/Models/Comment.php
class Comment extends Model {
    public function post() {
        return $this->belongsTo(Post::class);
    }
}

In the migrations for comments, you would make sure they have a foreign key that references the posts table:

// database/migrations/create_comments_table.php
Schema::create('comments', function (Blueprint $table) {
    $table->id();
    $table->foreignId('post_id')->constrained();
    $table->text('content');
    $table->timestamps();
});

Retrieving Records

To access the comments for a specific post you can do:

$post = Post::find(1);
$comments = $post->comments;

Eloquent will take care of joining the appropriate tables behind the scenes.

With the relationships set up, adding a comment to a post becomes trivial:

$comment = new Comment(['content' => 'A new comment.']);
$post->comments()->save($comment);

This will automatically attach the new comment to the post it belongs to.

Advanced Usage

You can also use powerful methods like whereHas and with to filter posts based on their related comments:

$posts = Post::whereHas('comments', function($query) {
    $query->where('content', 'like', '%first%');
})->get();

This will fetch posts which have comments containing the word ‘first’.

Lazy loading can pose a performance issue, so it’s better to eager load relationships which can be accomplished with with:

$posts = Post::with('comments')->get();

This will bring in all related comments for the posts in a single query.

Dealing with Multiple Relationships

In a more complex scenario, where you might have multiple layers of one-to-many relationships (e.g., users have posts, which have comments), the power of Eloquent really shines:

// In the User model
public function posts() {
    return $this->hasMany(Post::class);
}

// To retrieve all comments for all posts by a single user
$user = User::with('posts.comments')->find(1);

Conclusion

Mastering one-to-many relationships in Eloquent helps shift your focus from database management to developing the actual features of your application. The eloquence of Eloquent ORM’s syntax fosters clean and readable code, making your job as a developer more enjoyable.

Next Article: Using many-to-many relationships in Eloquent (with examples)

Previous Article: Eloquent: 5 Ways to Exclude Specific Columns from Query Result

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array