Files

43 lines
1.3 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Http\Controllers;
use App\Models\WeightLog;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class WeightLogController extends Controller
{
public function store(Request $request): RedirectResponse
{
$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();
// updateOrCreate's raw match array compares logged_at as a literal string,
// which doesn't reliably match how the `date` cast stores it - use a
// date-aware lookup instead.
$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 back()->with('status', __('app.weight_log.saved'));
}
public function destroy(WeightLog $weightLog): RedirectResponse
{
if ($weightLog->user_id !== Auth::id()) {
abort(403);
}
$weightLog->delete();
return back()->with('status', __('app.weight_log.deleted'));
}
}