Files
crud-laravel/app/Http/Controllers/PostController.php
2024-05-21 14:17:55 +08:00

100 lines
3.0 KiB
PHP

<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
class PostController extends Controller
{
/**
* Retrieve all posts with their associated user.
*
* @return \Illuminate\Http\JsonResponse A JSON response containing all posts.
*/
public function get()
{
$posts = Post::with('user')->get();
return response()->json($posts, 200);
}
/**
* Create a new post.
*
* @param Request $request The HTTP request object.
* @return \Illuminate\Http\JsonResponse A JSON response containing the created post.
*/
public function post(Request $request)
{
//OLD-------------
// $data = $request->all();
// $post = new Post($data);
// $post->user_id = auth()->id();
// $post->save();
// return response()->json($post, 201);
//NEW-----------------
$validator = Validator::make($request->all(), [
'content' => 'required',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
$post = Post::create([
'content' => $request->content,
'user_id' => auth()->id()
]);
//you can use the $post value for future "push" function of the JavaScript instead of fetching data every time with new posts
return response()->json($post, 201);
}
/**
* Update an existing post.
*
* @param Request $request The HTTP request object.
* @param int $postId The ID of the post to update.
* @return \Illuminate\Http\JsonResponse A JSON response containing the updated post or an error message.
*/
//OLD
// public function put(Request $request, $postId)
// {
// $post = Post::find($postId);
// if ($post && $post->user_id === auth()->id()) {
// $data = $request->all();
// $post->update($data);
// return response()->json($post, 200);
// } else {
// return response()->json(['error' => 'You are not authorized to update this post'], 401);
// }
// }
// }
//NEW
public function put(Request $request)
{
// below section is REQUIRED
$validator = Validator::make($request->all(), [
'content' => 'required',
]);
if ($validator->fails()) {
return response()->json($validator->errors(), 400);
}
$data = [
'content' => $request->content
];
// above section is REQUIRED
//only owner can update the
$post = Post::where([
'id' => $request->id,
'user_id' => auth()->id()
])->first();
//return empty post
if (!$post) {
return response()->json(['error' => "You are not authorized to update this post."], 401);
}
$post->update($data);
return response()->json($post, 200);
}
}