Create records using relationship in laravel

Updated at 20-Mar-2021, By samar

Create records using relationship in laravel

In this article, we will see how to solve "Create records using relationship in laravel".

  • --PATH app\Http\Controllers\<YourController.php>
    $post = Post::find(1);
    $comment = new Comment();
    $comment->comment = 'I love this blog post. Keep it up.';
    $post->comments()->save($comment);
    
    You can call relationship functions to create records in laravel. Like if you want to create a comment for a particular post you can use the comments() method which is a one to many relationship function in your post model.
  • --PATH app\Http\Controllers\<YourController.php>
    $post = Post::find(1);
     
    $post->comments()->saveMany([
        new Comment(['comment' => 'A new comment.']),
        new Comment(['comment' => 'Another new comment.']),
    ]);
    
    If you want to add multiple records using laravel Eloquent: Relationships. You can insert multiple records in your comments table using saveMany() method on comments() method which is one to many relationship method in your post model.

Back to code snippet queries related laravel