postOrder->apply( $this->postFilter->apply(Post::with(['category', 'tags', 'comments']), $filters), $orderDef )->paginate($this->paginate, page: $page); return PaginableResource::createFromLengthAwarePaginator($posts); } public function findPost(int $id): ?Post { return Post::with(['category', 'tags', 'comments'])->find($id); } public function storePost(array $data): Post { DB::beginTransaction(); $post = Post::create($data); if (isset($data['tags'])) { $tags = []; foreach ($data['tags'] as $tag) { $tag = Tag::firstOrCreate(['name' => $tag]); $tags[] = $tag; } $post->tags()->sync($tags); } $post = $this->findPost($post->id); if ($post === null) { throw new \InvalidArgumentException('This should never happen - post is null'); } DB::commit(); return $post; } public function updatePost(array $data, int $id): ?Post { DB::beginTransaction(); $post = Post::find($id); if ($post === null) { return null; } if (isset($data['tags'])) { $tags = []; foreach ($data['tags'] as $tag) { $tag = Tag::firstOrCreate(['name' => $tag]); $tags[] = $tag; } $post->tags()->sync($tags); } $post->update($data); DB::commit(); return $this->findPost($post->id); } public function deletePost(int $id): bool { $post = Post::find($id); if ($post === null) { return false; } $post->delete(); return true; } }