84 lines
1.9 KiB
PHP
84 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Http\Requests\StorePostRequest;
|
|
use App\Http\Requests\UpdatePostRequest;
|
|
use App\Http\Resources\PostCollection;
|
|
use App\Http\Resources\PostResource;
|
|
use App\Models\Post;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
|
|
class PostController extends Controller
|
|
{
|
|
/**
|
|
* Display a listing of posts.
|
|
*/
|
|
public function index(): PostCollection
|
|
{
|
|
$posts = Post::with('user')->latest()->paginate(15);
|
|
return new PostCollection($posts);
|
|
}
|
|
|
|
/**
|
|
* Store a newly created post.
|
|
*/
|
|
public function store(StorePostRequest $request): JsonResponse
|
|
{
|
|
$post = Post::create([
|
|
'title' => $request->title,
|
|
'content' => $request->content,
|
|
'user_id' => $request->user()->id,
|
|
]);
|
|
|
|
$post->load('user');
|
|
|
|
return response()->json([
|
|
'message' => 'Post created successfully',
|
|
'post' => new PostResource($post),
|
|
], 201);
|
|
}
|
|
|
|
/**
|
|
* Display the specified post.
|
|
*/
|
|
public function show(Post $post): JsonResponse
|
|
{
|
|
$post->load('user');
|
|
return response()->json([
|
|
'post' => new PostResource($post),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Update the specified post.
|
|
*/
|
|
public function update(UpdatePostRequest $request, Post $post): JsonResponse
|
|
{
|
|
$this->authorize('update', $post);
|
|
|
|
$post->update($request->validated());
|
|
|
|
return response()->json([
|
|
'message' => 'Post updated successfully',
|
|
'post' => new PostResource($post),
|
|
]);
|
|
}
|
|
|
|
/**
|
|
* Remove the specified post.
|
|
*/
|
|
public function destroy(Post $post): JsonResponse
|
|
{
|
|
$this->authorize('delete', $post);
|
|
|
|
$post->delete();
|
|
|
|
return response()->json([
|
|
'message' => 'Post deleted successfully',
|
|
]);
|
|
}
|
|
}
|