n How to use One To Many Eloquent Relationship in Laravel | CodimTh

Please Disable Your Browser Adblock Extension for our site and Refresh This Page!

our ads are user friendly, we do not serve popup ads. We serve responsible ads!

Refresh Page
Skip to main content
On . By CodimTh
Category:

In this tutorial, i would like to explain one to many model relationship in laravel. One to many model relationship is very simple and basic. One to Many relationship will use when one table associated with multiple tables. For example, a post may have multiple comments.

In this example, I will create a "posts" table and "comments" table. both tables are connected with each other. now we will create one to many relationships with each other by using the laravel Eloquent Model. 

One to OMany Relationship will use "hasMany()" and "belongsTo()" for relation.

Create Migrations:

Now we have to create migration of "posts" and "comments" tables . so let's create like as below:

 

posts table migration:


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

comments table migration:

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

});

 

Create Models:

Here, we will create Post and Comment table model. we will also use "hasMany()" and "belongsTo()" for relationship of both model.

 

Post Model:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{
    /**
     * Get the comments for the blog post.
     */
    public function comments()
    {
        return $this->hasMany(Comment::class);
    }
}

 

Comment Model:

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;

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

 

Retrieve Records:

Retrieve comments from Post object:

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

Retrieve post from Comment object:

$post = Comment::find(1)->post;

to add condition to comments you can use comments() method like this and add where ...:

$comments = App\Post::find(1)->comments()->where('title', 'test')->get();

Create Records:

Eloquent provides convenient methods for adding new models to relationships. For example, you need to insert a new comment for a Post model. Instead of manually setting the post_id attribute on the Comment, you may insert the Comment directly from the relationship's save method:

$post = Post::find(1);

$comment = new Comment();

$comment->comment = "Lorem ipsum";

$post = $post->comments()->save($comment);

 

Record multiple:

$post = Post::find(1);

$comment1 = new Comment();

$comment1->comment = "Comment 1";

$comment2 = new Comment();

$comment2->comment = "Comment 2";

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

 

When updating a belongsTo relationship, you may use the associate method. This method will set the foreign key on the child model: 

$comment = Comment::find(1);

$post = Post::find(2);

$comment->post()->associate($post)->save();

 

I hope you found this article useful. let me know if you have any questions and I’ll be happy to answer them.

Riadh Rahmi

Senior Web Developer PHP/Drupal & Laravel

I am a senior web developer, I have experience in planning and developing large scale dynamic web solutions especially in Drupal & Laravel.

Web Posts

Search

Page Facebook