File: /home/posscale/public_html/printmanager/app/Models/AlertThreshold.php
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class AlertThreshold extends Model
{
use HasFactory;
protected $fillable = [
'printer_instance_id',
'toner_ink_id',
'tenant_id',
'threshold',
];
public function getPrinterNameTenantAttribute()
{
// Ensure tenant_id exists
if (! $this->tenant_id) {
return 'Unknown';
}
tenancy()->initialize($this->tenant_id);
$printer = \App\Models\Printer::find($this->printer_instance_id);
$name = $printer->model_name ?? 'Unknown Printer';
$name .= " ".($printer->equipment_id ??'');
tenancy()->end();
return $name;
}
public function tenant(): BelongsTo
{
return $this->belongsTo(\App\Models\Tenant::class, 'tenant_id');
}
public function getCustomerNameAttribute()
{
return $this->tenant()->first()->customer_name;
}
protected static function booted()
{
static::creating(function ($model) {
if (empty($model->toner_ink_id) && $model->printer_instance_id) {
$model->toner_ink_id = \App\Models\TonerLevelMonitoring::where('id', $model->printer_instance_id)
->value('toner_ink_id');
$model->tenant_id = \App\Models\TonerLevelMonitoring::where('id', $model->printer_instance_id)
->value('tenant_id');
}
});
static::updating(function ($model) {
// If printer_instance_id has changed OR toner_ink_id is missing
if ($model->isDirty('printer_instance_id')) {
$model->toner_ink_id = \App\Models\TonerLevelMonitoring::where('id', $model->printer_instance_id)
->value('toner_ink_id');
$model->tenant_id = \App\Models\TonerLevelMonitoring::where('id', $model->printer_instance_id)
->value('tenant_id');
}
});
}
}