Laravel One to Many (hasMany) Relationship Example

One to Many relationship is to define relationships where a single model owns any amount of other models. For example, a post may have multiple comments so we can get use the hasMany or belongsTo to get the all comments of a post. In this tutorial we will show you best example to use one to many eloquent relationship in laravel 6, laravel 7, laravel 8 or laravel 9.

We explain you how to create migration with a foreign key schema for one to many relationships, create records, retrive records parents with child or child to associted parent table everything related to one to many relationships.

One to Many Relationship in Laravel

One to Many Relationship associate with hasMany() methods in laravel.

Follow the following steps to use one to many relationship in laravel app;

  • Step 1: Download Laravel App
  • Step 2: Connect App to Database
  • Step 3: Create Model And Migration
  • Step 4: Set One To Many Relationship
  • Step 5: Inverse Of The Relationship
  • Step 6: One to Many Usage

Download Laravel App

First create new laravel application adding the following command in terminal.

composer create-project laravel/laravel --prefer-dist laravel-relationship

Go into the app

laravel-relationship

Connect Database to App

In this step, we need to add the database credentials in .env file like following:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Create Model and Migration

Next step, we need to execute the following commands on terminal for create Post and Comment 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 create_posts_table.php migration file from database/migrations and replace up() function with following code:

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

Now open create_comments_table.php migration file from database/migrations and replace up() function with following code:

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');
    });
}

Next, migrate the table using the below command:

php artisan migrate

Set One To Many Relationship

A post may have an multiple number of comments, so we use hasMany function for getting comments. so open the Post model and set relation like below:

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); // we can also include comment model like: 'App\Models\Comment'
    }
}

Inverse Of The Relationship

We can access the Comment model from our Post. We can define the inverse of a hasMany relationship using the belongsTo method.

<?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);
    }
}

One to Many Usage

Now let’s have a look at some usage of onetoMany relationship for getting records from both parent and child tables.

Retrive Records:

public function index()
{
    $post = Post::find(1);
    $comments = $post->comments;

    dd($comments);
}

If you are geetings the comments table post then you can get like:

public function index()
{
    $comment = Comment::find(1);
    $post = $comment->post;

    dd($post);
}

Insert Records:

Inserting data in databse with child table your can use like below:

public function store()
{
    $post = Post::find(1);
    $comment = new Comment;
    $comment->comment = "This is teset comment";
     
    $post = $post->comments()->save($comment);
}

Also use like:

public function store()
{
    $post = Post::find(1);
    $comment1 = new Comment;
    $comment1->comment = "This is first comment";

    $comment2 = new Comment;
    $comment2->comment = "This is second comment";

    $post = $post->comments()->saveMany([$comment1, $comment2]);
}

See Also: Laravel Eloquent One to One Relationship Example Tutorial

So dear, the laravel one to many (hasMany) eloquent relationship tutorial is over now. Feel free to comments and follow us on social networks.

1 thought on “Laravel One to Many (hasMany) Relationship Example”

Leave a Comment