Laravel Eloquent One to Many Relationship Tutorial with Example

Published on October 13, 2020 1 min read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

A one-to-many relationship is used to define relationships where a single model owns any amount of other models. For example, a blog post may have an infinite number of comments. This article last tested on Laravel 8.x.

In this article, I’ll show one to many and it’s reverse relationship. I’ll create relation between Post and Comment models. Here’s the schema design:

Table of Contents

  1. Install Laravel and Basic Configurations
  2. Create Migration and Model
  3. Set One To Many Relationship
  4. Inverse Of The Relationship
  5. Usage

Install Laravel and Basic Configurations

Each Laravel project needs this thing. That’s why I have written an article on this topic. Please see this part from here: Install Laravel and Basic Configurations.

Create Migration and Model

Let’s create post and command models with migration files:

# create post model & migration
php artisan make:model Post -m

# create comment model & migration
php artisan make:model Comment -m

Now open the posts migration file from database>migrations directory and update up() function:

create_posts_table.php
public function up()
{
    Schema::create('posts', function (Blueprint $table) {
        $table->id();
        $table->string('title');
        $table->string('body');
        $table->timestamps();
    });
}

Like posts migration file, update comment migration’s up() function:

create_comments_table.php
public function up()
{
    Schema::create('comments', function (Blueprint $table) {
        $table->id();
        $table->unsignedBigInteger('post_id');
        $table->string('comment');
        $table->timestamps();

        $table->foreign('post_id')->references('id')->on('posts')
            ->onDelete('cascade');
    });
}

We have set post_id as a foreign key. So the comment/s will be deleted if we delete the post.

Set One To Many Relationship

A blog post may have an infinite number of comments. We have to use hasMany function to get comments. Open Post model and set relation like:

app/Models/Post.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    use HasFactory;

    /**
     * Get the comments for the post.
     */
    public function comments()
    {
        return $this->hasMany(Comment::class);
        // note: we can also include comment model like: 'App\Models\Comment'
    }
}

Inverse Of The Relationship

We can access the Comment model from our Post. Now, let’s define a relationship on the Comment model that will let us access the Post that owns the comments. We can define the inverse of a hasMany relationship using the belongsTo method.

app/Models/Comment.php
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Comment extends Model
{
    use HasFactory;

    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

Usage

Now let’s have a look at some usage of this relationship.

Insert Records:

// insert 1 post
$post = new Post();
$post->title = "Test post";
$post->body = "Post body goes here";
$post->save();

// insert 2 comments
$comment = new Comment();
$comment->post_id = 1;
$comment->comment = "Comment text 1";
$comment->save();

$comment = new Comment();
$comment->post_id = 1;
$comment->comment = "Comment text 2";
$comment->save();

Retrive Records:

// get all comments of a post
$id = 1;
$post = Post::find($id);
$all_comments = $post->comments;
dd($all_comments);

// get the post of a comment
$id = 1;
$comment = Comment::find($id);
$post = $comment->post;
dd($post);
To get more details of one to one eloquent relationship, you can read Laravel’s official documentation.

The tutorial is over. Thanks for reading. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *