Laravel One to Many Eloquent Relationship Tutorial With Example

  • 21-04-2022
  • 1393
  • Laravel 7
  • Haresh Chauhan

Laravel One To Many Relation one of the laravel powerfull tools to find out the parent child relation, by using hasmany relation laravel find the main parent with it's child apart from this laravel also providing one to one relation and many to many relation in laravel. Here the laravel determine the relation one model to other child model.

In this post you will learn how to make relation one to many in laravel eloquent. in this relation will have more than one relation with it's child. Here we can take the example of post and it's comment or author and it's post's can easy to find the relation with the help of laravel has many relation.

In this example we are taking post and comment, using the laravel hasmany relation we will find the post with it's comment.


Create company migration or what you wants create.

Here this example start from migration if you still not clone the laravel project please clone new fresh laravel project

Step 1 : Create post migration

In the first step will create post migration this post table will we create post from their author. the below command will create posts table with post model.

php artisan make:model Post -m

Now you can see the migration in given root

database/migration

<?php
    
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreatePostsTable extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('author_name');
            $table->string('post_description');
            $table->timestamps();
        });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::dropIfExists('posts');
    }
}

Read Also :Laravel One to One Eloquent Relationship Tutorial

Step 2 : Create comment migration

In this step comment migration will create with comment model, this comment model will as child.

php artisan make:model Comment -m

Now you can see the migration in given root there is two migration first is posts and second for comment database/migration

<?php

use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateCommentsTable extends Migration
{
    /**
    * Run the migrations.
    *
    * @return void
    */
    public function up()
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->unsignedBigInteger('post_id');
            $table->string('name');
            $table->string('comment');
            $table->tinyInteger('rate');
            $table->timestamps();
        });
    }

    /**
    * Reverse the migrations.
    *
    * @return void
    */
    public function down()
    {
        Schema::dropIfExists('comments');
    }
}

Step 3 : Create relation in post model

Here this step will create relation with Comment, we will user laravel hasmany relation.

App/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,'post_id','id');
    }
}

Step 4 : Create relation in comment model

In this step reverse relationship will create can find post from comment.

App/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,'id','post_id');
    }
}

Step 5 : Create route

Create route in routes/web.php

<?php

use Illuminate\Support\Facades\Route;
    
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/
    
Route::get('/post', 'PostController@index')->name('post');

Step 6 : Create post controller

Will create post controller for run the route and example App/Http/Controllers/PostController.php

<?php
    
namespace App\Http\Controllers;

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

class PostController extends Controller
{
    /**
    * Show the application dashboard.
    *
    * @return \Illuminate\Contracts\Support\Renderable
    */

    public function index()
    {
        // FIND FIRST POST FROM AUTHORNAME

        $post = Post::where('author_name','jakson')->first();

        dd($post->comment);
        dd($post->comment->comment);

        // FIND POST FROM Comment

        $comment = Comment::find(1);

        dd($comment->post);
        dd($comment->post->title);
    }
}

Apart from this eloquent also pre defind default foreign key, also you can make by define you self with id.


We always thanks to you for reading our blogs.


dharmesh-image

Dharmesh Chauhan

(Swapinfoway Founder)

Hello Sir, We are brothers origin from Gujarat India, Fullstack developers working together since 2016. We have lots of skills in web development in different technologies here I mention PHP, Laravel, Javascript, Vuejs, Ajax, API, Payment Gateway Integration, Database, HTML5, CSS3, and Server Administration. So you need our service Please Contact Us

haresh-image

Haresh Chauhan

(Co-Founder)


We Are Also Recommending You :