mirror of
https://github.com/henry4682/finance_app.git
synced 2026-07-16 00:10:00 +00:00
65 lines
1.6 KiB
PHP
65 lines
1.6 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Api;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Models\Category;
|
|
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
|
|
use Illuminate\Http\Request;
|
|
|
|
class CategoryController extends Controller
|
|
{
|
|
use AuthorizesRequests;
|
|
|
|
/**
|
|
* 新增分類
|
|
* POST /api/categories
|
|
*/
|
|
public function store(Request $request)
|
|
{
|
|
$validated = $request->validate([
|
|
'name' => 'required|string|max:255',
|
|
'color' => 'nullable|string|max:7',
|
|
'icon' => 'nullable|string|max:50',
|
|
]);
|
|
|
|
$category = Category::create([
|
|
...$validated,
|
|
'user_id' => $request->user()->id,
|
|
]);
|
|
|
|
// 🟢 修正:回傳剛剛建立的 JSON 資料與 201 狀態碼給前端 push 入陣列
|
|
return response()->json($category, 201);
|
|
}
|
|
|
|
/**
|
|
* 修改分類
|
|
* PUT /api/categories/{category}
|
|
*/
|
|
public function update(Request $request, Category $category)
|
|
{
|
|
$this->authorize('update', $category);
|
|
|
|
$validated = $request->validate([
|
|
'name' => 'required|string|max:255',
|
|
'color' => 'nullable|string|max:7',
|
|
]);
|
|
|
|
$category->update($validated);
|
|
|
|
// 🟢 修正:回傳修改後的最新資料,讓前端動態替換
|
|
return response()->json($category);
|
|
}
|
|
|
|
/**
|
|
* 刪除分類
|
|
* DELETE /api/categories/{category}
|
|
*/
|
|
public function destroy(Category $category)
|
|
{
|
|
$this->authorize('delete', $category);
|
|
$category->delete();
|
|
|
|
return response()->json(['message' => '分類刪除成功']);
|
|
}
|
|
} |