favorites

This commit is contained in:
2025-10-02 23:52:07 +03:00
parent dee8c09298
commit 1ed9235451
12 changed files with 194 additions and 2 deletions
@@ -0,0 +1,47 @@
<?php
namespace App\Http\Controllers;
use App\Models\Exercise;
use App\Models\Workout;
use Illuminate\Http\RedirectResponse;
use Illuminate\Support\Facades\Auth;
class FavoriteController extends Controller
{
public function __construct()
{
$this->middleware('auth');
}
public function toggleExercise(Exercise $exercise): RedirectResponse
{
$user = Auth::user();
$exists = $user->favoriteExercises()->where('exercise_id', $exercise->id)->exists();
if ($exists) {
$user->favoriteExercises()->detach($exercise->id);
$msg = 'Removed from favorites';
} else {
$user->favoriteExercises()->attach($exercise->id);
$msg = 'Added to favorites';
}
return back()->with('status', $msg);
}
public function toggleWorkout(Workout $workout): RedirectResponse
{
$user = Auth::user();
if ($workout->user_id && $workout->user_id !== $user->id) {
// Users can still favorite others' workouts if shared later; for now no restriction besides existence
}
$exists = $user->favoriteWorkouts()->where('workout_id', $workout->id)->exists();
if ($exists) {
$user->favoriteWorkouts()->detach($workout->id);
$msg = 'Removed from favorites';
} else {
$user->favoriteWorkouts()->attach($workout->id);
$msg = 'Added to favorites';
}
return back()->with('status', $msg);
}
}
+5
View File
@@ -39,4 +39,9 @@ class Exercise extends Model
{
return $this->hasMany(WorkoutExercise::class);
}
public function favoritedBy()
{
return $this->belongsToMany(User::class, 'exercise_favorites')->withTimestamps();
}
}
+21
View File
@@ -51,4 +51,25 @@ class User extends Authenticatable
{
return $this->hasMany(Workout::class);
}
public function favoriteExercises()
{
return $this->belongsToMany(Exercise::class, 'exercise_favorites')->withTimestamps();
}
public function favoriteWorkouts()
{
return $this->belongsToMany(Workout::class, 'workout_favorites')->withTimestamps();
}
// Helpers
public function hasFavoritedExercise(Exercise $exercise): bool
{
return $this->favoriteExercises()->where('exercise_id', $exercise->id)->exists();
}
public function hasFavoritedWorkout(Workout $workout): bool
{
return $this->favoriteWorkouts()->where('workout_id', $workout->id)->exists();
}
}
+5
View File
@@ -40,4 +40,9 @@ class Workout extends Model
->withTimestamps()
->orderBy('workout_exercises.position');
}
public function favoritedBy()
{
return $this->belongsToMany(User::class, 'workout_favorites')->withTimestamps();
}
}