It seems okay to use the create()
method to insert a document record. However, for the sake of efficiency there is a method to create multiple models in a single call. Per the Laravel documentation for The create
Method:
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.'],
]);
1
To use that, the storeAttachments
method could be updated to store the attributes to be inserted into an array and then that array could be passed to the createMany()
method, something like the (untested) code below:
public function storeAttachments(Stream $stream, InboundEmail $email)
{
$attributes = [];
foreach ($email->attachments() as $attachment) {
//Set an unique filename
$filename = uniqid() . '.' . File::extension($attachment->getFilename());
//Store the file on the server
$store = Storage::put($stream->token . '/' . $filename, $attachment->getContent());
//Add attributes to the array of attributes to be inserted
$attributes[] = [
'name' => $attachment->getFilename(),
'path' => $stream->token . '/' . $filename
];
}
//Persist it to the database.
$stream->documents()->createMany($attributes);
}
The creation of $attributes
could be simplified using the map()
collection method, though it would require extra function calls:
public function storeAttachments(Stream $stream, InboundEmail $email)
{
$attributes = $email->attachments()->map(function ($attachment) use ($stream) {
//Set an unique filename
$filename = uniqid() . '.' . File::extension($attachment->getFilename());
//Store the file on the server
$store = Storage::put($stream->token . '/' . $filename, $attachment->getContent());
//Add attributes to the array of attributes to be inserted
return [
'name' => $attachment->getFilename(),
'path' => $stream->token . '/' . $filename
];
});
//Persist it to the database.
$stream->documents()->createMany($attributes);
}