Veranstaltungen-APP/app/Models/Location.php

125 lines
2.8 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Support\Str;
class Location extends Model
{
use SoftDeletes;
protected $fillable = [
'name',
'slug',
'description',
'street',
'house_number',
'postal_code',
'city',
'state',
'country',
'latitude',
'longitude',
'phone',
'email',
'website',
];
protected $casts = [
'created_at' => 'datetime',
'updated_at' => 'datetime',
'deleted_at' => 'datetime',
'latitude' => 'float',
'longitude' => 'float',
];
/**
* Ein Ort hat viele Events.
*/
public function events(): HasMany
{
return $this->hasMany(Event::class);
}
/**
* Scope: Nach Name filtern (case-insensitive)
*/
public function scopeByName($query, $name)
{
return $query->where('name', 'like', '%' . $name . '%');
}
/**
* Scope: Nach Stadt filtern
*/
public function scopeByCity($query, $city)
{
return $query->where('city', 'like', '%' . $city . '%');
}
/**
* Boot-Methode: Auto-generate slug
*/
protected static function boot()
{
parent::boot();
static::creating(function ($location) {
if (!$location->slug) {
$location->slug = Str::slug($location->name);
}
});
static::updating(function ($location) {
if (!$location->slug || $location->isDirty('name')) {
$location->slug = Str::slug($location->name);
}
});
}
/**
* Getter: Vollständige Adresse
*/
public function getFullAddressAttribute(): string
{
$parts = [];
// Straße und Hausnummer
if ($this->street) {
$parts[] = $this->street . ($this->house_number ? ' ' . $this->house_number : '');
}
// PLZ und Stadt
if ($this->postal_code || $this->city) {
$parts[] = trim(($this->postal_code ?? '') . ' ' . ($this->city ?? ''));
}
// Bundesland (falls vorhanden)
if ($this->state && $this->state !== $this->city) {
$parts[] = $this->state;
}
// Land
if ($this->country) {
$parts[] = $this->country;
}
return implode(', ', array_filter($parts));
}
/**
* Getter: Kurze Adresse (Stadt/Ort)
*/
public function getShortAddressAttribute(): string
{
$parts = array_filter([
$this->postal_code,
$this->city,
]);
return implode(' ', $parts) ?: $this->name;
}
}