ItSolutionStuff.com

Laravel 12 One to Many Eloquent Relationship Tutorial

By Hardik Savani • April 3, 2025
Laravel

I will show you how to use one to many relationship in laravel 12 application. we will use hasMany() and belongsTo() method of eloquent.

In Laravel 12, a one-to-many relationship between a "posts" table and a "comments" table means that one post can have many comments, but each comment belongs to only one post. So, a post can have multiple comments associated with it, but each comment is linked to just one post. This relationship is established by defining the appropriate relationships in the models, making it easy to fetch comments belonging to a specific post.

laravel 12 one to many relationship

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

Create Migrations:

Now we have to create a migration for the "posts" and "comments" tables. We will also add a foreign key to the "posts" table. So let's create it as below:

posts table migration:

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('posts', function (Blueprint $table) {
            $table->id();
            $table->string("name");
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('posts');
    }
};

comments table migration:

<?php
  
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
  
return new class extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up(): void
    {
        Schema::create('comments', function (Blueprint $table) {
            $table->id();
            $table->foreignId('post_id')->constrained('posts');
            $table->string("comment");
            $table->timestamps();
        });
    }
  
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down(): void
    {
        Schema::dropIfExists('comments');
    }
};

Create Models:

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

app/Models/Post.php

<?php
  
namespace App\Models;
  
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
  
class Post extends Model
{
    use HasFactory;
 
    /**
     * Get the comments for the blog post.
     *   
     * Syntax: return $this->hasMany(Comment::class, 'foreign_key', 'local_key');
     *
     * Example: return $this->hasMany(Comment::class, 'post_id', 'id');
     * 
     */
    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }
}

app/Models/Comment.php

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

Retrieve Records:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $comments = Post::find(1)->comments;
  
        dd($comments);
    }
}

<?php
 
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Comment;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $post = Comment::find(1)->post;
  
        dd($post);
    }
}

Create Records:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
use App\Models\Comment;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $post = Post::find(1);
   
        $comment = new Comment;
        $comment->comment = "Hi ItSolutionStuff.com";
           
        $post = $post->comments()->save($comment);
    }
}

<?php
  
namespace App\Http\Controllers;
   
use Illuminate\Http\Request;
use App\Models\Post;
use App\Models\Comment;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $post = Post::find(1);
   
        $comment1 = new Comment;
        $comment1->comment = "Hi ItSolutionStuff.com Comment 1";
           
        $comment2 = new Comment;
        $comment2->comment = "Hi ItSolutionStuff.com Comment 2";
           
        $post = $post->comments()->saveMany([$comment1, $comment2]);
    }
}

<?php
   
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\Post;
use App\Models\Comment;
  
class PostController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index(Request $request)
    {
        $comment = Comment::find(1);
        $post = Post::find(2);
           
        $comment->post()->associate($post)->save();
    }
}

I hope you understand of one to many relationship...

Hardik Savani

Hardik Savani

I'm a full-stack developer, entrepreneur, and founder of ItSolutionStuff.com. Passionate about PHP, Laravel, JavaScript, and helping developers grow.

📺 Subscribe on YouTube

We Are Recommending You

Laravel 12 Many to Many Eloquent Relationship Tutorial

Read Now →

Laravel 12 Has Many Through Relationship Example

Read Now →

Laravel 12 One to One Relationship Example

Read Now →

Laravel 12 Generate QR Code Example Tutorial

Read Now →

How to Get Current Full URL in Laravel 12?

Read Now →

Laravel 12 Resize Image Before Upload Example

Read Now →

Laravel 12 Ajax CRUD Operation Tutorial

Read Now →

Laravel 12 Create Custom Error Page Example

Read Now →

Laravel 12 JQuery UI Ajax Autocomplete Search

Read Now →

Laravel 12 Flash Message Example Example

Read Now →

Image Upload with Progress Bar in Angular 12

Read Now →

File Uploading in Angular 12 Tutorial

Read Now →

Angular 12 Reactive Forms Validation Example

Read Now →