Model Relationhsip in Laravel

Hello World, Today i am going to discuss model relationship in laravel. We will extends our previous tutorial in which we fetch data from database with ajax in laravel. In previous tutorial, We are fetching posts from database. In this tutorial, We will add comments in database to specific post and then fetch specific post comments with One to Many Relationship.

I have divided this tutorial in following steps:

  • About model relationship
  • About eloquent ORM
  • One to Many Relationship
  • Define comment model
  • Define One to Many relationship
  • Fetch specific post comments with model relationship in post controller
  • Create post detail blade template
  • Add some dummy comments with laravel factory
  • Run the project


model Relationship

Database tables are often related to one another. For example, a blog post have many comments or a user have many photos. In laravel, we can manage these relationship very easily with Eloquent ORM.


Eloquent ORM

Eloquent is ORM which comes with laravel. Eloquent provides simple Active Record implementation for working with database. Every table has a corresponding “model” which is use to interact with that table.In laravel, model is known as Eloquent model which responsible to perform database queries in tables.


One to Many

A one-to-many relationship is used to define relationships where a single model owns any amount of other models.


Define Comment model

Open command or terminal and enter the following command to create command model and migration in laravel.

php artisan make:model Comment -m

Above command will create two files, One in app folder and another is in database/migrations folder. Open newly created comment migration file and add the following code to create comment table.

Schema::create('comments', function (Blueprint $table) {
            $table->increments('id');
            $table->string('email');
            $table->string('comment');
            $table->timestamps();
        });

Define One to Many relationship

As we know that post can have many comments. To define relationship in post with comments we will follow the following steps.

  • Open Post model and add the following method code in it.
  • function comments(){
        	return $this->hasMany('App\Comment');
        }

    Above method will connect post model with comments model with hasMany method.


Fetch specific post comments with model relationship in post controller

In this step, we will modify PostController file. Perform the following steps to fetch and show comments of specific post with model relationship.

  • Open PostController file and add the following method in it.
// Single Post
    function single_post($post_id){
        $comments=Post::find($post_id)->comment;
        $postDetail=Post::find($post_id);
        return view('post-detail',[
            'postDetail'=>$postDetail,
            'comments'=>$comments
        ]);
    }

Create post detail blade template

In this step, we will create post detail template in which we will show all comments of specific post.

  • Create post-detail.blade.php file in **/resources/views** folder and add the following code in it.
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Ajax Fetch Data</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" />
</head>
<body>
    <div class="container mt-4">
        <div class="border p-3 mb-4 shadow-sm">
            <h3 class="border-bottom pb-2">{{ $postDetail->title }}</h3>
            <p>{{ $postDetail->body }}</p>
        </div>
        <hr />
        <h3 class="mt-4 pb-2">Comments</h3>
        @if(count($comments)>0)
            @foreach($comments as $comment)
                <blockquote class="blockquote shadow-sm border p-3 bg-light mb-3">
                    <p class="mb-0">{{$comment->comment}}</p>
                    <footer class="blockquote-footer">{{$comment->email}}</footer>
                </blockquote>
            @endforeach
        @endif
    </div>
</body>
</html>

Add some dummy comments with laravel factory

In this step, we will add some dummy data in comments table with random post id. In the previous tutorial, we have added posts with laravel factory class. Here we will apply the same method. Add the following code in database/factories/UserFactory.php file.

// Generate Comments
$factory->define(App\Comment::class, function (Faker $faker) {
    return [
        'post_id'=>App\Post::all()->random()->id,
        'email' => $faker->unique()->safeEmail,
        'comment' => $faker->text,
    ];
});

Run the project

After doing the long work, its time to run the project. Please open in this project on your browser.

  • Click on fetch post button.
  • Now click on the Specific post.
  • You will see the all comments just below the post body.

I hope you enjoyed this tutorial.Please add your feedback in comment section below. 🙂 🙂

Leave a Reply

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