75 lines
2.3 KiB
PHP
75 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Http\Response;
|
|
|
|
use App\Models\Post;
|
|
|
|
class PostsController extends Controller
|
|
{
|
|
public function getFields(Request $request, $post) {
|
|
// Retrieve the post by the 'body' column (UUID)
|
|
$post = Post::where('body', $post)->first();
|
|
|
|
// If the post is not found, return a 404 response
|
|
if (!$post) {
|
|
return response()->json(['message' => 'Post not found'], Response::HTTP_NOT_FOUND);
|
|
}
|
|
|
|
// Retrieve all stores associated with this post
|
|
$stores = $post->stores;
|
|
|
|
// Prepare the response data
|
|
$fields = $stores->map(function ($store) {
|
|
return [
|
|
'key' => $store->key,
|
|
'values' => $store->values,
|
|
];
|
|
});
|
|
|
|
// Return the JSON response with the fields
|
|
return response()->json(['fields' => $fields], Response::HTTP_OK);
|
|
}
|
|
|
|
public function storePost(Request $request) {
|
|
// Validate the request body
|
|
$request->validate([
|
|
'body' => 'required|uuid', // Ensure the body is a valid UUID
|
|
]);
|
|
|
|
// Check if a post with the same UUID already exists
|
|
$existingPost = Post::where('body', $request->body)->first();
|
|
|
|
if ($existingPost) {
|
|
// Return a 409 Conflict response if the post already exists
|
|
return response()->json(['message' => 'Post with this UUID already exists'], Response::HTTP_CONFLICT);
|
|
}
|
|
|
|
// Create a new post
|
|
$post = Post::create([
|
|
'body' => $request->body,
|
|
]);
|
|
|
|
// Return a 201 Created response with the created post
|
|
return response()->json(['message' => 'Post created successfully', 'post' => $post], Response::HTTP_CREATED);
|
|
}
|
|
|
|
public function deletePost($post) {
|
|
// Retrieve the post by the 'body' column (UUID)
|
|
$post = Post::where('body', $post)->first();
|
|
|
|
// If the post is not found, return a 404 response
|
|
if (!$post) {
|
|
return response()->json(['message' => 'Post not found'], Response::HTTP_NOT_FOUND);
|
|
}
|
|
|
|
// Delete the post
|
|
$post->delete();
|
|
|
|
// Return a 200 OK response with a success message
|
|
return response()->json(['message' => 'Post deleted successfully'], Response::HTTP_OK);
|
|
}
|
|
}
|