Add body weight logging with a trend on the dashboard
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>
This commit is contained in:
@@ -49,13 +49,21 @@ class DashboardController extends Controller
|
|||||||
->groupBy(function ($s) { return $s->created_at->format('Y-m-d'); })
|
->groupBy(function ($s) { return $s->created_at->format('Y-m-d'); })
|
||||||
->map->count();
|
->map->count();
|
||||||
|
|
||||||
|
// Body weight trend
|
||||||
|
$weightLogs = $user->weightLogs()->orderBy('logged_at')->get(['id', 'weight_kg', 'logged_at']);
|
||||||
|
$weightChange = $weightLogs->count() >= 2
|
||||||
|
? round($weightLogs->last()->weight_kg - $weightLogs->first()->weight_kg, 2)
|
||||||
|
: null;
|
||||||
|
|
||||||
return view('dashboard', compact(
|
return view('dashboard', compact(
|
||||||
'workoutsCount',
|
'workoutsCount',
|
||||||
'sessionsCount',
|
'sessionsCount',
|
||||||
'completedSessions',
|
'completedSessions',
|
||||||
'completionRate',
|
'completionRate',
|
||||||
'recentSessions',
|
'recentSessions',
|
||||||
'dailyActivity'
|
'dailyActivity',
|
||||||
|
'weightLogs',
|
||||||
|
'weightChange'
|
||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,42 @@
|
|||||||
|
<?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'));
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -84,6 +84,11 @@ class User extends Authenticatable
|
|||||||
return $this->belongsToMany(YogaPose::class, 'yoga_pose_favorites')->withTimestamps();
|
return $this->belongsToMany(YogaPose::class, 'yoga_pose_favorites')->withTimestamps();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public function weightLogs()
|
||||||
|
{
|
||||||
|
return $this->hasMany(WeightLog::class);
|
||||||
|
}
|
||||||
|
|
||||||
// Helpers
|
// Helpers
|
||||||
public function hasFavoritedExercise(Exercise $exercise): bool
|
public function hasFavoritedExercise(Exercise $exercise): bool
|
||||||
{
|
{
|
||||||
|
|||||||
@@ -0,0 +1,28 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace App\Models;
|
||||||
|
|
||||||
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||||
|
use Illuminate\Database\Eloquent\Model;
|
||||||
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||||
|
|
||||||
|
class WeightLog extends Model
|
||||||
|
{
|
||||||
|
use HasFactory;
|
||||||
|
|
||||||
|
protected $fillable = [
|
||||||
|
'user_id',
|
||||||
|
'weight_kg',
|
||||||
|
'logged_at',
|
||||||
|
];
|
||||||
|
|
||||||
|
protected $casts = [
|
||||||
|
'weight_kg' => 'decimal:2',
|
||||||
|
'logged_at' => 'date',
|
||||||
|
];
|
||||||
|
|
||||||
|
public function user(): BelongsTo
|
||||||
|
{
|
||||||
|
return $this->belongsTo(User::class);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Database\Factories;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use Illuminate\Database\Eloquent\Factories\Factory;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\WeightLog>
|
||||||
|
*/
|
||||||
|
class WeightLogFactory extends Factory
|
||||||
|
{
|
||||||
|
public function definition(): array
|
||||||
|
{
|
||||||
|
return [
|
||||||
|
'user_id' => User::factory(),
|
||||||
|
'weight_kg' => fake()->randomFloat(1, 55, 110),
|
||||||
|
'logged_at' => fake()->dateTimeBetween('-60 days', 'now')->format('Y-m-d'),
|
||||||
|
];
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,32 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
use Illuminate\Database\Migrations\Migration;
|
||||||
|
use Illuminate\Database\Schema\Blueprint;
|
||||||
|
use Illuminate\Support\Facades\Schema;
|
||||||
|
|
||||||
|
return new class extends Migration
|
||||||
|
{
|
||||||
|
/**
|
||||||
|
* Run the migrations.
|
||||||
|
*/
|
||||||
|
public function up(): void
|
||||||
|
{
|
||||||
|
Schema::create('weight_logs', function (Blueprint $table) {
|
||||||
|
$table->id();
|
||||||
|
$table->foreignId('user_id')->constrained()->cascadeOnDelete();
|
||||||
|
$table->decimal('weight_kg', 5, 2);
|
||||||
|
$table->date('logged_at');
|
||||||
|
$table->timestamps();
|
||||||
|
|
||||||
|
$table->unique(['user_id', 'logged_at']);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Reverse the migrations.
|
||||||
|
*/
|
||||||
|
public function down(): void
|
||||||
|
{
|
||||||
|
Schema::dropIfExists('weight_logs');
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -231,6 +231,19 @@ return [
|
|||||||
'activity_30d_help' => 'Number of sessions per day (higher is better).',
|
'activity_30d_help' => 'Number of sessions per day (higher is better).',
|
||||||
],
|
],
|
||||||
|
|
||||||
|
'weight_log' => [
|
||||||
|
'title' => 'Body Weight',
|
||||||
|
'change_since_first' => 'Change since your first entry:',
|
||||||
|
'weight_kg' => 'Weight (kg)',
|
||||||
|
'date' => 'Date',
|
||||||
|
'log' => 'Log',
|
||||||
|
'none' => 'No weight entries yet. Log your first one to start tracking your trend.',
|
||||||
|
'saved' => 'Weight logged',
|
||||||
|
'deleted' => 'Entry deleted',
|
||||||
|
'delete' => 'Delete',
|
||||||
|
'confirm_delete' => 'Delete this entry?',
|
||||||
|
],
|
||||||
|
|
||||||
'admin' => [
|
'admin' => [
|
||||||
'title' => 'Admin Dashboard',
|
'title' => 'Admin Dashboard',
|
||||||
'subtitle' => 'Manage content and see overall site statistics.',
|
'subtitle' => 'Manage content and see overall site statistics.',
|
||||||
|
|||||||
@@ -231,6 +231,19 @@ return [
|
|||||||
'activity_30d_help' => 'Număr de sesiuni pe zi (mai mult este mai bine).',
|
'activity_30d_help' => 'Număr de sesiuni pe zi (mai mult este mai bine).',
|
||||||
],
|
],
|
||||||
|
|
||||||
|
'weight_log' => [
|
||||||
|
'title' => 'Greutate corporală',
|
||||||
|
'change_since_first' => 'Schimbare de la prima înregistrare:',
|
||||||
|
'weight_kg' => 'Greutate (kg)',
|
||||||
|
'date' => 'Data',
|
||||||
|
'log' => 'Adaugă',
|
||||||
|
'none' => 'Nicio înregistrare încă. Adaugă prima pentru a-ți urmări evoluția.',
|
||||||
|
'saved' => 'Greutate înregistrată',
|
||||||
|
'deleted' => 'Înregistrare ștearsă',
|
||||||
|
'delete' => 'Șterge',
|
||||||
|
'confirm_delete' => 'Ștergi această înregistrare?',
|
||||||
|
],
|
||||||
|
|
||||||
'admin' => [
|
'admin' => [
|
||||||
'title' => 'Panou de administrare',
|
'title' => 'Panou de administrare',
|
||||||
'subtitle' => 'Gestionează conținutul și vezi statisticile generale ale site‑ului.',
|
'subtitle' => 'Gestionează conținutul și vezi statisticile generale ale site‑ului.',
|
||||||
|
|||||||
@@ -88,5 +88,51 @@
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
<div class="mt-8 rounded-2xl ring-1 ring-gray-200 dark:ring-gray-700 bg-white dark:bg-gray-800 p-5">
|
||||||
|
<div class="flex items-center justify-between flex-wrap gap-3">
|
||||||
|
<div>
|
||||||
|
<h2 class="text-lg font-semibold text-gray-900 dark:text-white">{{ __('app.weight_log.title') }}</h2>
|
||||||
|
@if($weightChange !== null)
|
||||||
|
<p class="mt-1 text-sm text-gray-600 dark:text-gray-300">
|
||||||
|
{{ __('app.weight_log.change_since_first') }}
|
||||||
|
<span class="font-semibold {{ $weightChange < 0 ? 'text-emerald-600' : ($weightChange > 0 ? 'text-amber-600' : 'text-gray-600') }}">
|
||||||
|
{{ $weightChange > 0 ? '+' : '' }}{{ $weightChange }} kg
|
||||||
|
</span>
|
||||||
|
</p>
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
|
<form method="POST" action="{{ route('weight-logs.store') }}" class="flex items-end gap-2">
|
||||||
|
@csrf
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400">{{ __('app.weight_log.weight_kg') }}</label>
|
||||||
|
<input type="number" step="0.1" min="20" max="400" name="weight_kg" required class="mt-1 w-28 rounded-lg border-gray-300 dark:border-gray-700 bg-white/80 dark:bg-gray-900 text-gray-900 dark:text-gray-100 px-3 py-2 text-sm">
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label class="block text-xs font-medium text-gray-500 dark:text-gray-400">{{ __('app.weight_log.date') }}</label>
|
||||||
|
<input type="date" name="logged_at" max="{{ now()->toDateString() }}" value="{{ now()->toDateString() }}" class="mt-1 rounded-lg border-gray-300 dark:border-gray-700 bg-white/80 dark:bg-gray-900 text-gray-900 dark:text-gray-100 px-3 py-2 text-sm">
|
||||||
|
</div>
|
||||||
|
<button type="submit" class="inline-flex items-center rounded-lg bg-indigo-600 px-3 py-2 text-sm font-semibold text-white hover:bg-indigo-500">{{ __('app.weight_log.log') }}</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
@if($weightLogs->isEmpty())
|
||||||
|
<div class="mt-4 rounded-xl border border-dashed border-gray-300 dark:border-gray-700 p-6 text-sm text-gray-600 dark:text-gray-300">{{ __('app.weight_log.none') }}</div>
|
||||||
|
@else
|
||||||
|
<div class="mt-4 flex flex-wrap gap-2">
|
||||||
|
@foreach($weightLogs->reverse()->take(10) as $log)
|
||||||
|
<div class="inline-flex items-center gap-2 rounded-full bg-gray-100 dark:bg-gray-900 ring-1 ring-gray-200 dark:ring-gray-700 pl-3 pr-1.5 py-1 text-sm">
|
||||||
|
<span class="font-semibold text-gray-900 dark:text-white">{{ rtrim(rtrim(number_format($log->weight_kg, 1), '0'), '.') }} kg</span>
|
||||||
|
<span class="text-gray-500">{{ $log->logged_at->format('M j') }}</span>
|
||||||
|
<form method="POST" action="{{ route('weight-logs.destroy', $log) }}" onsubmit="return confirm('{{ __('app.weight_log.confirm_delete') }}');">
|
||||||
|
@csrf
|
||||||
|
@method('DELETE')
|
||||||
|
<button type="submit" class="text-gray-400 hover:text-red-500 rounded-full h-5 w-5 inline-flex items-center justify-center" aria-label="{{ __('app.weight_log.delete') }}">×</button>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
@endforeach
|
||||||
|
</div>
|
||||||
|
@endif
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
</x-app-layout>
|
</x-app-layout>
|
||||||
|
|||||||
@@ -30,6 +30,10 @@ Route::middleware('auth')->group(function () {
|
|||||||
|
|
||||||
// Exercise alias (per-user rename)
|
// Exercise alias (per-user rename)
|
||||||
Route::post('/exercises/{exercise}/alias', [\App\Http\Controllers\ExerciseAliasController::class, 'store'])->name('exercises.alias');
|
Route::post('/exercises/{exercise}/alias', [\App\Http\Controllers\ExerciseAliasController::class, 'store'])->name('exercises.alias');
|
||||||
|
|
||||||
|
// Body weight log
|
||||||
|
Route::post('/weight-logs', [\App\Http\Controllers\WeightLogController::class, 'store'])->name('weight-logs.store');
|
||||||
|
Route::delete('/weight-logs/{weightLog}', [\App\Http\Controllers\WeightLogController::class, 'destroy'])->name('weight-logs.destroy');
|
||||||
});
|
});
|
||||||
|
|
||||||
Route::prefix('/exercises')->group(function () {
|
Route::prefix('/exercises')->group(function () {
|
||||||
|
|||||||
@@ -0,0 +1,89 @@
|
|||||||
|
<?php
|
||||||
|
|
||||||
|
namespace Tests\Feature;
|
||||||
|
|
||||||
|
use App\Models\User;
|
||||||
|
use App\Models\WeightLog;
|
||||||
|
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||||
|
use Tests\TestCase;
|
||||||
|
|
||||||
|
class WeightLogTest extends TestCase
|
||||||
|
{
|
||||||
|
use RefreshDatabase;
|
||||||
|
|
||||||
|
public function test_guest_cannot_log_weight(): void
|
||||||
|
{
|
||||||
|
$response = $this->post(route('weight-logs.store'), ['weight_kg' => 80]);
|
||||||
|
|
||||||
|
$response->assertRedirect(route('login'));
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_user_can_log_weight_for_today(): void
|
||||||
|
{
|
||||||
|
$user = User::factory()->create();
|
||||||
|
|
||||||
|
$response = $this->actingAs($user)->post(route('weight-logs.store'), [
|
||||||
|
'weight_kg' => 82.5,
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response->assertRedirect();
|
||||||
|
$entry = WeightLog::where('user_id', $user->id)->first();
|
||||||
|
$this->assertNotNull($entry);
|
||||||
|
$this->assertEquals(82.5, $entry->weight_kg);
|
||||||
|
$this->assertEquals(now()->toDateString(), $entry->logged_at->toDateString());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_logging_twice_for_the_same_date_updates_the_entry(): void
|
||||||
|
{
|
||||||
|
$user = User::factory()->create();
|
||||||
|
|
||||||
|
$this->actingAs($user)->post(route('weight-logs.store'), [
|
||||||
|
'weight_kg' => 80,
|
||||||
|
'logged_at' => '2026-01-01',
|
||||||
|
]);
|
||||||
|
$this->actingAs($user)->post(route('weight-logs.store'), [
|
||||||
|
'weight_kg' => 81,
|
||||||
|
'logged_at' => '2026-01-01',
|
||||||
|
]);
|
||||||
|
|
||||||
|
$this->assertEquals(1, WeightLog::where('user_id', $user->id)->count());
|
||||||
|
$entry = WeightLog::where('user_id', $user->id)->first();
|
||||||
|
$this->assertEquals(81, $entry->weight_kg);
|
||||||
|
$this->assertEquals('2026-01-01', $entry->logged_at->toDateString());
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_future_date_is_rejected(): void
|
||||||
|
{
|
||||||
|
$user = User::factory()->create();
|
||||||
|
|
||||||
|
$response = $this->actingAs($user)->post(route('weight-logs.store'), [
|
||||||
|
'weight_kg' => 80,
|
||||||
|
'logged_at' => now()->addDay()->toDateString(),
|
||||||
|
]);
|
||||||
|
|
||||||
|
$response->assertSessionHasErrors('logged_at');
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_owner_can_delete_their_entry(): void
|
||||||
|
{
|
||||||
|
$user = User::factory()->create();
|
||||||
|
$log = WeightLog::factory()->create(['user_id' => $user->id]);
|
||||||
|
|
||||||
|
$response = $this->actingAs($user)->delete(route('weight-logs.destroy', $log));
|
||||||
|
|
||||||
|
$response->assertRedirect();
|
||||||
|
$this->assertDatabaseMissing('weight_logs', ['id' => $log->id]);
|
||||||
|
}
|
||||||
|
|
||||||
|
public function test_other_user_cannot_delete_someone_elses_entry(): void
|
||||||
|
{
|
||||||
|
$owner = User::factory()->create();
|
||||||
|
$other = User::factory()->create();
|
||||||
|
$log = WeightLog::factory()->create(['user_id' => $owner->id]);
|
||||||
|
|
||||||
|
$response = $this->actingAs($other)->delete(route('weight-logs.destroy', $log));
|
||||||
|
|
||||||
|
$response->assertForbidden();
|
||||||
|
$this->assertDatabaseHas('weight_logs', ['id' => $log->id]);
|
||||||
|
}
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user