
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
- Laravel clone model
- Retrieve count of nested relationship data in Laravel
- Permanently delete a record in laravel
- Laravel order by date not working
- How to check relationship is loaded or not in Laravel
- How to start websocket server in laravel
- Property [user] does not exist on this collection instance
- Laravel create table migration with model
- Pagination in laravel
- Get last year created records in Laravel
- How to get only time from created_at in laravel
- Create project factory and seed data in laravel
- Convert input array to comma-separated string in laravel controller
- How to display 1 day ago in comments in laravel view
- Create model with migration and seeder
- How to pass link from controller to view in laravel on ajax call
- How to remove P tag from CkEditor in Laravel?
- How to include header file in laravel
- Laravel API response format
- How to customize or Change validation error messages
- Get latest record by created at in Laravel
- Automatically remove records using Prunable trait in Laravel
- Ignore Records where a field has NULL value in Laravel
- Argument 1 passed to Illuminate\Database\Query\Builder::cleanBindings() must be of the type array, null given
- How to check records exist in loaded relationship in Laravel blade view