Create records using relationship in laravel

Answers 2
  • --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);
    
    0
    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.']),
    ]);
    
    0
    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