In a relational database management system, we know database tables are related to one another. For example, a post may have many comments or an order could be related to the user who placed it. Laravel eloquent makes managing and working with these relationships very convenient. Laravel provides many relationships and in this tutorial, I will show you how we handle one to many or we can call this hasMany eloquent relationship.

In this Laravel 9 one to many relationship example tutorial, I am going to use the Post and Comments concept. Suppose, A post may have many comments and a comment may be related to one post. Let's see how we can define Laravel's one to many relationship. 

We can use the hasMany() method to define one to many relationships and the first argument passed to the hasMany method is the name of the related model class. In this example, I will create a posts table and a comments table. Now I will create one to many relationships with each other by using the Laravel Eloquent Model.

laravel-9-one-to-many-relationship-tutorial

Now assume we have a table like below:

posts table:

Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string("name");
    $table->timestamps();
});

 

comments table:

Schema::create('comments', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('post_id')->unsigned();
    $table->string("comment");
    $table->timestamps();
    $table->foreign('post_id')->references('id')->on('posts')
        ->onDelete('cascade');
});

 

Defining One To Many Relationship

Our table is ready, now we can define one to many or hasmany eloquent relationship by the following way:

app\Models\Post.php

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

 

If we avoid foreign like above, then remember Laravel Eloquent will assume the foreign key column on the Comment model is post_id. Now we can find every comment of a single post like:

App\Http\Controllers\TestController.php

<?php

namespace App\Http\Controllers;

use App\Models\Post;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index($id)
    {   
        $comments = Post::find($id)->comments;

        foreach ($comments as $comment) {
          //
        }
    }
}

 

Defining Inverse Relationship of hasMany

Now we know how to define hasMany or one to many relationships. Now we will see how we can define the inverse relationship of hasMany. Let's define a relationship on the Comment model that will let us access the post. We can define the inverse of a hasMany relationship using the belongsTo method like:

app/Models/Comment.php

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Comment extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo(Post::class);
    }
}

 

Read also: Laravel One To One/HasOne Eloquent Relationship Tutorial

 

Here we can also pass fereign_key and local_key like below:

<?php
 
namespace App\Models;
 
use Illuminate\Database\Eloquent\Model;
 
class Comment extends Model
{
    /**
     * Get the post that owns the comment.
     */
    public function post()
    {
        return $this->belongsTo(Post::class,'foreign_key', 'owner_key');
    }
}

 

Now we can also fetch post like:

App\Http\Controllers\TestController.php

<?php

namespace App\Http\Controllers;

use App\Models\Comment;
use Illuminate\Http\Request;

class TestController extends Controller
{
    public function index($id)
    {   
        $comment = Comment::find($id);
        return $comment->post->title;
    }
}

 

Read also: Complete Explanation With Example On Laravel Middleware

 

Conclusion

Now we can know laravel 9 one to may relationship and how it works. Hope this Laravel 9 hasMany relationship tutorials will help you.