When one table is linked to numerous tables, a one-to-many relationship is used. A post, for example, could include many comments. In the examples of Laravel 6, Laravel 7, Laravel 8, and Laravel 9, there is an eloquent one-to-many relationship.
So, in this tutorial, you'll learn how to establish a one-to-many relationship migration using a foreign key schema, how to utilise sync with a pivot table, how to add records, obtain all data, delete, update, and everything else related to one-to-many relationships.
I'll make a "posts" table and a "comments" table in this example. Both tables are linked to one another. Using the Laravel Eloquent Model, we'll now construct one-to-many relationships with each other. We'll start with database migration, then move on to modeling, retrieving records, and finally creating records. 

"hasMany()" and "belongsTo()" will be used for relation in a One to Many Relationship.

1. Create Migrations

The "posts" and "comments" tables must now be migrated. With the posts table, we'll also add a foreign key. So, let's make something like this:

Posts table migration

Schema::create('posts', function (Blueprint $table) {
    $table->increments('id');
    $table->string("name");
    $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');
});

2. Create Models

We'll make a Post and Comment table model here. For both models' relationships, we'll use "hasMany()" and "belongsTo()."

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);
    }
}
?>

3. Retrieve Records

$post = Post::find(1);
$comments = $post->comments;
dd($comments);
$comment = Comment::find(1);
$post = $comment->post;
dd($post);

4. Create Records

$post = Post::find(1);
$comment = new Comment;
$comment->comment = "Hi CodeSolutionStuff";
$post = $post->comments()->save($comment);
$post = Post::find(1);
$comment1 = new Comment;
$comment1->comment = "Hi CodeSolutionStuff Comment 1";
$comment2 = new Comment;
$comment2->comment = "Hi CodeSolutionStuff Comment 2";
$post = $post->comments()->saveMany([$comment1, $comment2]);
$comment = Comment::find(1);
$post = Post::find(2);
$comment->post()->associate($post)->save();

I hope you will like the content and it will help you to learn Laravel One to Many Eloquent Relationship
If you like this content, do share.


Recommended Posts

View All

Laravel Google Chart Example Tutorial


laravel google chart example, dynamic charts in laravel, laravel google pie chart, laravel google line chart example, google chart in laravel, laravel...

Laravel 9 Socialite Login with Facebook Tutorial


In this tutorial, we'll learn how to use the Socialite package in Laravel to login with a Facebook social networking account.

Laravel 9 Form Validation Example


In this Laravel 9 validation tutorial, I'll demonstrate how to validate form input and provide an error message before saving it to the database.

Laravel 8 Generate PDF File using DomPDF | Laravel 8 PDF


How to generate pdf from view, html, blade in laravel 8. Here, we would share with you how to generate pdf file from blade view in laravel 8

Laravel Full Text Search with Scout


You will have learned how the scout elastic search functions from today's tutorial