lernschiff/app/Models/User.php

85 lines
2.4 KiB
PHP

<?php
namespace App\Models;
use App\Scopes\TenantScope;
use App\Traits\BelongsToTenant;
use App\Traits\HasUuid;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable, HasUuid, BelongsToTenant, SoftDeletes;
protected $fillable = ['name', 'email', 'password', 'tenant_id'];
protected $hidden = ['password', 'remember_token', 'id'];
protected $casts = ['email_verified_at' => 'datetime', 'password' => 'hashed'];
public function role()
{
return $this->belongsToMany(Role::class, 'role_user')->withTimestamps();
}
public function hasRole(string $role): bool
{
$this->loadMissing('role');
return $this->role->contains('name', $role);
}
public function hasAnyRole(array $roles): bool
{
foreach ($roles as $role) {
if ($this->hasRole($role)) {
return true;
}
}
return false;
}
public function tenant()
{
return $this->belongsTo(Tenant::class);
}
public function licenseAssignments()
{
return $this->hasMany(LicenseAssignment::class);
}
public function children()
{
return $this->belongsToMany(User::class, 'parent_child', 'parent_id', 'child_id')
->using(ParentChild::class)
->withTimestamps()
->withoutGlobalScope(\App\Scopes\TenantScope::class);
}
public function parents()
{
return $this->belongsToMany(User::class, 'parent_child', 'child_id', 'parent_id')
->using(ParentChild::class)
->withTimestamps()
->withoutGlobalScope(\App\Scopes\TenantScope::class);
}
protected static function booted(): void
{
static::deleting(function (User $user) {
if ($user->isForceDeleting()) {
return; // FK cascadeOnDelete handles hard-delete
}
\DB::table('role_user')->where('user_id', $user->id)->delete();
\DB::table('license_assignments')->where('user_id', $user->id)->delete();
\DB::table('parent_child')
->where('parent_id', $user->id)
->orWhere('child_id', $user->id)
->delete();
});
}
}