No way existed to log body weight over time - only the single
self-reported value from the signup profile - and the dashboard showed
session activity but nothing about physical progress, which is usually
the main reason people keep using a fitness app.
Adds a WeightLog model (one entry per user per day, re-logging the same
day updates it rather than duplicating), a quick-add form and trend
summary on the dashboard, and delete support.
Found and fixed a real bug along the way: the first implementation used
WeightLog::updateOrCreate() with a raw ['logged_at' => $date] match
array, which silently failed to find the same-day entry because the
`date` cast stores full datetime strings ('2026-01-01 00:00:00') while
the match array holds a plain 'Y-m-d' string - so re-logging the same
day hit a unique-constraint violation instead of updating. Fixed by
using a whereDate() lookup instead, which is comparison-format-safe.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
43 lines
1.3 KiB
PHP
43 lines
1.3 KiB
PHP
<?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'));
|
|
}
|
|
}
|