37074-vm/app/Http/Controllers/Api/PostController.php
Flatlogic Bot c2cb4a5b67 1.0
2025-12-19 19:07:10 +00:00

83 lines
1.7 KiB
PHP

<?php
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
class PostController extends Controller
{
/**
* Create a new PostController instance.
*/
public function __construct()
{
// Protect write routes with authentication
$this->middleware('auth:sanctum')->except(['index', 'show']);
}
/**
* Display a listing of the resource.
*/
public function index()
{
return Post::paginate(15);
}
/**
* Store a newly created resource in storage.
*/
public function store(Request $request)
{
Gate::authorize('create', Post::class);
$validated = $request->validate([
'title' => 'required|string|max:255',
'body' => 'required|string',
]);
$post = Post::create($validated);
return response()->json($post, 201);
}
/**
* Display the specified resource.
*/
public function show(Post $post)
{
return $post;
}
/**
* Update the specified resource in storage.
*/
public function update(Request $request, Post $post)
{
Gate::authorize('update', $post);
$validated = $request->validate([
'title' => 'sometimes|required|string|max:255',
'body' => 'sometimes|required|string',
]);
$post->update($validated);
return response()->json($post);
}
/**
* Remove the specified resource from storage.
*/
public function destroy(Post $post)
{
Gate::authorize('delete', $post);
$post->delete();
return response()->json(null, 204);
}
}