LMIV-SNACKAUTOMAT/app/Models/Setting.php

89 lines
2.1 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $fillable = [
'key',
'value',
'type',
'group',
'label',
'description',
'tenant_id'
];
/**
* Get the value with proper type casting
*/
public function getValueAttribute($value)
{
switch ($this->type) {
case 'boolean':
return (bool) $value;
case 'integer':
return (int) $value;
case 'json':
return json_decode($value, true);
default:
return $value;
}
}
/**
* Set the value with proper type conversion
*/
public function setValueAttribute($value)
{
switch ($this->type) {
case 'boolean':
$this->attributes['value'] = $value ? '1' : '0';
break;
case 'json':
$this->attributes['value'] = json_encode($value);
break;
default:
$this->attributes['value'] = $value;
}
}
/**
* Beziehung zum Mandanten
*/
public function tenant()
{
return $this->belongsTo(Tenant::class);
}
/**
* Get a setting value by key (mandanten-spezifisch)
*/
public static function get(string $key, $default = null, ?int $tenantId = null)
{
$tenantId = $tenantId ?? auth()->user()?->tenant_id;
$setting = static::where('key', $key)
->where('tenant_id', $tenantId)
->first();
return $setting ? $setting->value : $default;
}
/**
* Set a setting value by key (mandanten-spezifisch)
*/
public static function set(string $key, $value, ?int $tenantId = null): void
{
$tenantId = $tenantId ?? auth()->user()?->tenant_id;
$setting = static::where('key', $key)
->where('tenant_id', $tenantId)
->first();
if ($setting) {
$setting->update(['value' => $value]);
}
}
}