Settings.php 1.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace App\Models;
  3. use Illuminate\Database\Eloquent\Factories\HasFactory;
  4. use Illuminate\Database\Eloquent\Model;
  5. use Illuminate\Support\Facades\Cache;
  6. class Settings extends Model
  7. {
  8. use HasFactory;
  9. protected $table = 'settings';
  10. public const CACHE_TAG = 'setting';
  11. public $primaryKey = 'key';
  12. public $incrementing = false;
  13. protected $keyType = 'string';
  14. protected $fillable = [
  15. 'key',
  16. 'value',
  17. 'type',
  18. ];
  19. public static function boot()
  20. {
  21. parent::boot();
  22. static::updated(function (Settings $settings) {
  23. Cache::forget(self::CACHE_TAG.':'.$settings->key);
  24. });
  25. }
  26. /**
  27. * @param string $key
  28. * @param $default
  29. * @return mixed
  30. */
  31. public static function getValueByKey(string $key, $default = null)
  32. {
  33. return Cache::rememberForever(self::CACHE_TAG.':'.$key, function () use ($default, $key) {
  34. $settings = self::find($key);
  35. return $settings ? $settings->value : $default;
  36. });
  37. }
  38. }