49 lines
1.4 KiB
PHP
49 lines
1.4 KiB
PHP
<?php
|
|||
|
|
|
||
|
|
namespace App\Http\Controllers\Api;
|
||
|
|
|
||
|
|
use App\Http\Controllers\Controller;
|
||
|
|
use App\Http\Resources\WeightLogResource;
|
||
|
|
use App\Models\WeightLog;
|
||
|
|
use Illuminate\Http\JsonResponse;
|
||
|
|
use Illuminate\Http\Request;
|
||
|
|
use Illuminate\Support\Facades\Auth;
|
||
|
|
|
||
|
|
class WeightLogController extends Controller
|
||
|
|
{
|
||
|
|
public function index(): JsonResponse
|
||
|
|
{
|
||
|
|
$logs = Auth::user()->weightLogs()->orderBy('logged_at')->get();
|
||
|
|
|
||
|
|
return response()->json(['data' => WeightLogResource::collection($logs)]);
|
||
|
|
}
|
||
|
|
|
||
|
|
public function store(Request $request): JsonResponse
|
||
|
|
{
|
||
|
|
$data = $request->validate([
|
||
|
|
'weight_kg' => ['required', 'numeric', 'min:20', 'max:400'],
|
||
|
|
'logged_at' => ['nullable', 'date', 'before_or_equal:today'],
|
||
|
|
]);
|
||
|
|
|
||
|
|
$loggedAt = $data['logged_at'] ?? now()->toDateString();
|
||
|
|
|
||
|
|
$entry = WeightLog::where('user_id', Auth::id())->whereDate('logged_at', $loggedAt)->first()
|
||
|
|
?? new WeightLog(['user_id' => Auth::id(), 'logged_at' => $loggedAt]);
|
||
|
|
$entry->weight_kg = $data['weight_kg'];
|
||
|
|
$entry->save();
|
||
|
|
|
||
|
|
return response()->json(['weight_log' => new WeightLogResource($entry)], 201);
|
||
|
|
}
|
||
|
|
|
||
|
|
public function destroy(WeightLog $weightLog): JsonResponse
|
||
|
|
{
|
||
|
|
if ($weightLog->user_id !== Auth::id()) {
|
||
|
|
abort(403);
|
||
|
|
}
|
||
|
|
|
||
|
|
$weightLog->delete();
|
||
|
|
|
||
|
|
return response()->json(['message' => __('app.weight_log.deleted')]);
|
||
|
|
}
|
||
|
|
}
|