Create records using relationship in laravel

Created 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.';
    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);
        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

If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.

Buy Me A Coffee

Don't forget to share this article! Help us spread the word by clicking the share button below.

We appreciate your support and are committed to providing you valuable and informative content.

We are thankful for your never ending support.