I have some code which saves a post to a database, that goes well. Although I decided to add a little bit of extra code which saves the tags for a post in the same database.
But after adding this bit of code, my response time jumped to 25 seconds immediately. Am I using something that’s not recommended?
public function create($data)
{
$result = $this->repository->create($data);
if(!$result) {
throw new Exception('Post not created', 500);
}
dump('Created post: ', $result);
foreach ($data['contents'] as $index => $content) {
$content['post_id'] = $result->id;
$content['order'] = $index + 1;
$content = $this->postContentRepository->create($content);
dump('Created content: ', $content);
}
// The code below is causing the issue V
// Attach tags to the post
$tags = Tag::whereIn('name', $data['tags'])->get();
// Separate post-type tag and regular tags
$postTypeTag = $tags->where('type', 'post_type')->first();
$regularTags = $tags->where('type', 'tag');
// Attach tags in bulk
$tagIds = $regularTags->pluck('id')->toArray();
if ($postTypeTag) {
$tagIds[] = $postTypeTag->id;
}
$result->tags()->attach($tagIds);
return $result;
}
This is what a test request-body looks like:
{
"title": "My First Blog Post",
"user_id": 1,
"contents": [
{
"type": "paragraph",
"content": "This is the first paragraph of my blog post."
},
{
"type": "image",
"content": "https://example.com/path/to/image.jpg"
},
{
"type": "paragraph",
"content": "Here is some more text in my blog post."
},
{
"type": "video",
"content": "https://example.com/path/to/video.mp4"
}
],
"tags": [
"Discussion",
"Espresso",
"Equipment"
]
}