
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
- Cannot end a section without first starting one
- Update email with unique validation in laravel
- Display success message in laravel
- Target class [admin] does not exist.
- How to fill a column automatically while creating records in Laravel
- How to create belongstomany relation using custom name on custom pivot table
- Use withCount() to get total number of records with relationship
- Laravel pagination links with query string
- Composer create project laravel/laravel example app
- Get Array of IDs from Eloquent Collection
- How to get route method name in Laravel
- Get count of filter data, while return a small set of records
- SQLSTATE[42S21]: Column already exists: 1060 Duplicate column name 'user_id'
- How to add columns in existing table using migration in laravel
- Method Illuminate\Http\Request::validated does not exist
- Add a subselect based on relationship using withAggregate method
- Get posts belongs to a specific user in Laravel
- Symlink(): No such file or directory
- How to display pivot table column value in laravel
- Conditional validation in laravel
- Laravel route parameter
- SQLSTATE[42000]: Syntax error or access violation: 1055
- How to create projects method with belongstomany relationship in user model
- Create a record if not exist in laravel
- If no route matched route::fallback in laravel