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); } } }