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.'; $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.
If you like what you are reading, please consider buying us a coffee ( or 2 ) as a token of appreciation.
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.
Random Code Snippet Queries: Laravel
- Validation for multiple forms on same page in laravel
- Update email with unique validation in laravel
- How to authenticate admin users in Laravel ?
- How to fetch single row data from database in laravel
- How to add a key value pair to existing array in laravel
- Connection could not be established with host smtp.gmail.com :stream_socket_client(): unable to connect to tcp://smtp.gmail.com:587 (Connection refused)"
- How to add class to tr in table using foreach in laravel
- How to delete record in Laravel with ajax
- Wheredate in laravel not working
- How to send ID to another page in Laravel
- Laravel route redirect not working
- The openssl extension is required for SSL/TLS protection but is not available
- How to call controller function from view in Laravel
- How to insert multiple rows in mysql using loop in laravel?
- Laravel csrf token mismatch for ajax POST Request
- How to disable timestamps in laravel
- Display data in table using foreach in Laravel
- How to get route name on visit URL in laravel
- Method Illuminate\Http\Request::validated does not exist
- Get current URL on visit URL in Laravel
- How to create laravel project using composer
- How to use or operator in laravel
- Ajax GET request in laravel
- Create project factory and seed data in laravel
- Generate unique username in Laravel