Build out the trainer role

is_trainer was captured at signup and stored, but nothing in the app
used it - no client roster, no way to assign anything, a dead flag that
misled users who checked it during registration.

Adds a trainer/client link (a trainer adds a client by the email they
registered with) and lets a trainer create workouts directly on a
client's account (assigned_by_trainer_id on workouts). Deliberately
scoped for privacy: a trainer only ever sees/manages the workouts they
authored and assigned - not a client's other private data (their own
workouts, weight log, health notes, session/completion history). That
boundary needs a consent or notification system to relax safely, which
doesn't exist yet, so it's left for a follow-up rather than building it
half-safe.

WorkoutController's authorization now distinguishes "manage" (owner or
assigning trainer - view, add/edit exercises) from "own" (owner only -
delete), so a trainer can build out an assigned workout's exercises
after creating it, but can't delete a client's workout out from under
them.

Found a real bug via live testing before committing: the client roster
page eager-loaded `assignedWorkouts` (keyed by assigned_by_trainer_id)
on each client record, which is the trainer's own perspective, not the
client's - so it silently showed "no workouts assigned" even after
assigning one. Fixed to eager-load `workouts` filtered by
assigned_by_trainer_id instead, with a regression test.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
2026-08-10 12:28:23 +03:00
co-authored by Claude Sonnet 5
parent ebd0578dc9
commit e8173ff90a
17 changed files with 543 additions and 5 deletions
@@ -0,0 +1,92 @@
<?php
namespace App\Http\Controllers;
use App\Models\User;
use App\Models\Workout;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\View\View;
class TrainerController extends Controller
{
public function clients(): View
{
$trainer = Auth::user();
// Note: `workouts` (user_id) is what a client was assigned, not `assignedWorkouts`
// (assigned_by_trainer_id), which belongs to the trainer's own perspective.
$clients = $trainer->clients()
->with(['workouts' => function ($q) use ($trainer) {
$q->where('assigned_by_trainer_id', $trainer->id)->latest();
}])
->orderBy('name')
->get();
return view('trainer.clients', compact('clients'));
}
public function addClient(Request $request): RedirectResponse
{
$trainer = Auth::user();
$data = $request->validate([
'email' => ['required', 'email', 'exists:users,email'],
]);
$client = User::where('email', $data['email'])->firstOrFail();
if ($client->id === $trainer->id) {
return back()->withErrors(['email' => 'You cannot add yourself as a client.']);
}
if ($trainer->clients()->where('client_id', $client->id)->exists()) {
return back()->withErrors(['email' => 'This person is already one of your clients.']);
}
$trainer->clients()->attach($client->id);
return back()->with('status', 'Client added');
}
public function removeClient(User $client): RedirectResponse
{
Auth::user()->clients()->detach($client->id);
return back()->with('status', 'Client removed');
}
public function createWorkout(User $client): View
{
$this->authorizeClient($client);
return view('trainer.assign-workout', compact('client'));
}
public function storeWorkout(Request $request, User $client): RedirectResponse
{
$this->authorizeClient($client);
$data = $request->validate([
'title' => ['required', 'string', 'max:255'],
'notes' => ['nullable', 'string'],
'estimated_minutes' => ['nullable', 'integer', 'min:1', 'max:600'],
]);
$workout = Workout::create([
'user_id' => $client->id,
'assigned_by_trainer_id' => Auth::id(),
'title' => $data['title'],
'notes' => $data['notes'] ?? null,
'estimated_minutes' => $data['estimated_minutes'] ?? null,
]);
return redirect()->route('trainer.clients')->with('status', "Workout assigned to {$client->name}");
}
protected function authorizeClient(User $client): void
{
if (!Auth::user()->clients()->where('client_id', $client->id)->exists()) {
abort(403);
}
}
}
+15 -5
View File
@@ -17,7 +17,7 @@ class WorkoutController extends Controller
public function index()
{
$workouts = Auth::user()->workouts()->latest()->paginate(10);
$workouts = Auth::user()->workouts()->with('assignedByTrainer')->latest()->paginate(10);
return view('workouts.index', compact('workouts'));
}
@@ -41,7 +41,7 @@ class WorkoutController extends Controller
public function show(Workout $workout)
{
$this->authorizeWorkout($workout);
$workout->load(['items.exercise']);
$workout->load(['items.exercise', 'assignedByTrainer']);
$exercises = Exercise::orderBy('name')->limit(20)->get(['id','name','slug']);
return view('workouts.show', compact('workout', 'exercises'));
}
@@ -112,15 +112,25 @@ class WorkoutController extends Controller
public function destroy(Workout $workout)
{
$this->authorizeWorkout($workout);
// Deletion stays strictly owner-only, even for a trainer-assigned workout.
if ($workout->user_id !== Auth::id()) {
abort(403);
}
$workout->delete();
return redirect()->route('workouts.index')->with('status', 'Workout deleted');
}
// Allows the owner, or the trainer who assigned this workout, to view and edit it.
// Session/completion data is intentionally not exposed to the trainer here - only
// the workout structure they authored.
protected function authorizeWorkout(Workout $workout): void
{
if ($workout->user_id !== Auth::id()) {
abort(403);
if ($workout->user_id === Auth::id()) {
return;
}
if ($workout->assigned_by_trainer_id && $workout->assigned_by_trainer_id === Auth::id()) {
return;
}
abort(403);
}
}
+25
View File
@@ -0,0 +1,25 @@
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
class Trainer
{
/**
* Handle an incoming request.
*
* @param \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response) $next
*/
public function handle(Request $request, Closure $next): Response
{
$user = Auth::user();
if (!$user || !$user->is_trainer) {
abort(403);
}
return $next($request);
}
}
+16
View File
@@ -74,6 +74,22 @@ class User extends Authenticatable
return $this->hasMany(Program::class);
}
// Trainer/client relationships
public function clients()
{
return $this->belongsToMany(User::class, 'trainer_clients', 'trainer_id', 'client_id')->withTimestamps();
}
public function trainers()
{
return $this->belongsToMany(User::class, 'trainer_clients', 'client_id', 'trainer_id')->withTimestamps();
}
public function assignedWorkouts()
{
return $this->hasMany(Workout::class, 'assigned_by_trainer_id');
}
public function favoriteExercises()
{
return $this->belongsToMany(Exercise::class, 'exercise_favorites')->withTimestamps();
+6
View File
@@ -20,6 +20,7 @@ class Workout extends Model
'program_id',
'week_number',
'day_number',
'assigned_by_trainer_id',
];
protected $casts = [
@@ -38,6 +39,11 @@ class Workout extends Model
return $this->belongsTo(Program::class);
}
public function assignedByTrainer(): BelongsTo
{
return $this->belongsTo(User::class, 'assigned_by_trainer_id');
}
public function items(): HasMany
{
return $this->hasMany(WorkoutExercise::class)->orderBy('position');