Laravel One to Many Relationship

 Laravel One to Many Relationship



  •    Create Migrations :-

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


    Schema::create('comments', function (Blueprint $table) {
    $table->increments('id');
     $table->unsignedInteger('post_id');
    $table->string("comment");
     $table->timestamps();
     $table->foreign('post_id')->references('id')->on('posts')
->onDelete('cascade');
    });

  •   Create Model :-


    Post Model
    <?php

        namespace App;
        
        use Illuminate\Database\Eloquent\Model;

        class Post extends Model
        {
        public function comments()
        {
        return $this->hasMany(Comment::class);
        }
        }

    Comment Model
    <?php

    namespace App;

    use Illuminate\Database\Eloquent\Model;

    class Comment extends Model
    {
    public function post()
    {
     return $this->belongsTo(Post::class);
    }
    }

            $post = Post::find(1);

            $comments = $post->comments;

            dd($comments);
    

           $comment = Comment::find(1);

           $post = $comment->post;

           dd($post);

           $post = Post::find(1);

           $comment = new Comment;
           $comment->comment = "Hi Jaydeep";

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

    

            $post = Post::find(1);

            $comment1 = new Comment;
            $comment1->comment = "Hi Jaydeep";

            $comment2 = new Comment;
            $comment2->comment = "This is one to many relation.";

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


That's it that's one to many relationship. Enjoy it....😊😀😀



Comments

Post a Comment

Popular Posts

Laravel Hidden Eloquent Memory Leak: Why Your App Crashes with Large Data

Laravel Performance Optimization: 15 Proven Tips to Make Your App Faster (2026)

Laravel vs Node.js: Which Is Better for Web Development in 2026?