Laravel - Relationships - The Create Method
In addition to the
saveMany methods, you may also use the
create method, which accepts an array of attributes, creates a model, and inserts it into the database. The difference between
create is that
save accepts a full Eloquent model instance while
create accepts a plain PHP
array. The newly created model will be returned by the
use App\Models\Post; $post = Post::find(1); $comment = $post->comments()->create([ 'message' => 'A new comment.', ]);
You may use the
createMany method to create multiple related models:
$post = Post::find(1); $post->comments()->createMany([ ['message' => 'A new comment.'], ['message' => 'Another new comment.'], ]);
You may also use the
updateOrCreate methods to create and update models on relationships.
Before using the
createmethod, be sure to review the mass assignment documentation.