Files
fitness/app/Models/Exercise.php
T

87 lines
2.1 KiB
PHP
Raw Normal View History

2025-10-02 22:52:13 +03:00
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
2025-10-02 22:52:13 +03:00
use Illuminate\Database\Eloquent\Model;
2025-10-04 19:40:13 +03:00
use Illuminate\Support\Facades\Auth;
2025-10-06 22:35:04 +03:00
use Illuminate\Support\Facades\Storage;
2025-10-02 22:52:13 +03:00
class Exercise extends Model
{
use HasFactory;
2025-10-02 22:52:13 +03:00
protected $fillable = [
'name',
'slug',
'exercise_db_id',
'gif_url',
2025-10-06 22:35:04 +03:00
'poster_image',
2025-10-02 22:52:13 +03:00
'instructions',
];
// relations
public function targetMuscles()
{
return $this->belongsToMany(Muscle::class, 'exercise_target_muscle');
}
public function secondaryMuscles()
{
return $this->belongsToMany(Muscle::class, 'exercise_secondary_muscle');
}
public function bodyParts()
{
return $this->belongsToMany(BodyPart::class, 'body_part_exercise');
}
public function equipments()
{
return $this->belongsToMany(Equipment::class, 'equipment_exercise');
}
public function workoutExercises()
{
return $this->hasMany(WorkoutExercise::class);
}
2025-10-02 23:52:07 +03:00
public function favoritedBy()
{
return $this->belongsToMany(User::class, 'exercise_favorites')->withTimestamps();
}
2025-10-04 19:40:13 +03:00
public function aliases()
{
return $this->hasMany(ExerciseAlias::class);
}
public function getDisplayNameAttribute(): string
{
$name = (string) $this->attributes['name'] ?? '';
$userId = Auth::id();
if (!$userId) {
return $name;
}
// Use already loaded relation if present to avoid querying N+1
if ($this->relationLoaded('aliases')) {
$alias = $this->aliases->firstWhere('user_id', $userId);
return $alias?->name ?: $name;
}
$alias = $this->aliases()->where('user_id', $userId)->first();
return $alias?->name ?: $name;
}
2025-10-06 22:35:04 +03:00
public function getPosterUrlAttribute(): ?string
{
$poster = (string)($this->attributes['poster_image'] ?? '');
if ($poster === '') {
return null;
}
if (preg_match('/^https?:\/\//i', $poster)) {
return $poster;
}
return Storage::url($poster);
}
2025-10-02 22:52:13 +03:00
}