meals = User::getDefaultMeals(); // Set default API token. $user->api_token = Str::random(32); }); } /** * @inheritdoc */ protected $fillable = [ 'admin', 'api_token', 'meals', 'name', 'password', 'username', ]; /** * @inheritdoc */ protected $hidden = [ 'api_token', 'password', 'remember_token', ]; /** * @inheritdoc */ protected $casts = [ 'admin' => 'bool', 'meals' => AsCollection::class, ]; /** * Get the default meals structure. */ public static function getDefaultMeals(): Collection { $meals = new Collection(); for ($i = 0; $i <= 7; $i++) { $meals->add([ 'value' => $i, 'label' => 'Meal ' . ($i + 1), 'weight' => $i, 'enabled' => $i < 3, ]); } return $meals; } /** * @inheritdoc */ public function sluggable(): array { return ['slug' => ['source' => 'username']]; } /** * Get the User's goals. */ public function goals(): HasMany { return $this->hasMany(Goal::class); } /** * Get the User's journal dates. */ public function journalDates(): HasMany { return $this->hasMany(JournalDate::class); } /** * Get the User's journal entries. */ public function journalEntries(): HasMany { return $this->hasMany(JournalEntry::class); } /** * Get the User's enabled meals, sorted by weight. */ public function getMealsEnabledAttribute(): Collection { return $this->meals->where('enabled', true)->sortBy('weight'); } /** * Get user's goal (if one exists) for a specific date. * * The primary use for a JournalDate entry right now is the goal so this * method also creates a JournalDate if one does not already exist. */ public function getGoalByDate(Carbon $date): ?Goal { $journal_date = JournalDate::getOrCreateJournalDate($this, $date); if ($journal_date->goal) { return $journal_date->goal; } // Check for a goal based on day of week configurations. $day = Goal::days()->firstWhere('dow', $date->format('N')); if (!$day) { throw new \BadMethodCallException("No day with `dow` value {$date->format('N')}."); } /** @var \App\Models\Goal $goal */ $goal = $this->goals()->whereRaw("(days & {$day['value']}) != 0")->first(); if (!empty($goal)) { $journal_date->goal()->associate($goal); } if ($journal_date->hasChanges(['date', 'goal'])) { $journal_date->save(); } return $goal; } /** * Defines conversions for the User image. * * @throws \Spatie\Image\Exceptions\InvalidManipulation * * @see https://spatie.be/docs/laravel-medialibrary/v9/converting-images/defining-conversions */ public function registerMediaConversions(Media $media = null): void { $this->addMediaConversion('icon') ->width(300) ->height(300) ->sharpen(10) ->optimize(); } }