LMIV-SNACKAUTOMAT/app/Models/VendingMachine.php

94 lines
2.2 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
class VendingMachine extends Model
{
protected $fillable = [
'name',
'machine_number',
'slug',
'location',
'description',
'is_active',
'tenant_id'
];
protected $casts = [
'is_active' => 'boolean',
];
public function slots(): HasMany
{
return $this->hasMany(Slot::class);
}
public function activeSlots(): HasMany
{
return $this->hasMany(Slot::class)->where('is_active', true);
}
/**
* Beziehung zum Mandanten
*/
public function tenant()
{
return $this->belongsTo(Tenant::class);
}
/**
* Generiere einen eindeutigen Slug für diesen Mandanten
*/
public function generateSlug($name = null, $tenantId = null)
{
$name = $name ?: $this->name;
$tenantId = $tenantId ?: $this->tenant_id;
$baseSlug = \Illuminate\Support\Str::slug($name);
$slug = $baseSlug;
$counter = 1;
// Prüfe auf eindeutigen Slug innerhalb des Mandanten
while (static::where('tenant_id', $tenantId)
->where('slug', $slug)
->where('id', '!=', $this->id ?? 0)
->exists()) {
$slug = $baseSlug . '-' . $counter;
$counter++;
}
return $slug;
}
/**
* Boot-Method für automatische Slug-Generierung
*/
protected static function boot()
{
parent::boot();
static::creating(function ($machine) {
if (empty($machine->slug)) {
$machine->slug = $machine->generateSlug($machine->name, $machine->tenant_id);
}
});
static::updating(function ($machine) {
if ($machine->isDirty('name') && empty($machine->slug)) {
$machine->slug = $machine->generateSlug($machine->name, $machine->tenant_id);
}
});
}
/**
* Route Model Binding basierend auf Mandant und machine_number
*/
public function getRouteKeyName()
{
return 'machine_number';
}
}