Role.php
1 <?php 2 3 namespace App\Models; 4 5 use Illuminate\Database\Eloquent\Factories\HasFactory; 6 use Illuminate\Database\Eloquent\Model; 7 use Illuminate\Database\Eloquent\Relations\HasMany; 8 use Illuminate\Support\Facades\DB; 9 use Spatie\Activitylog\LogOptions; 10 use Spatie\Activitylog\Traits\LogsActivity; 11 12 class Role extends Model 13 { 14 use HasFactory, LogsActivity; 15 16 protected $table = 'roles'; 17 18 protected $guarded = []; 19 20 public static function getByName(string $name) 21 { 22 $role = static::query()->where('name', '=', $name)->firstOrFail(); 23 24 return $role; 25 } 26 27 public function parent() 28 { 29 return $this->belongsTo(Role::class,'parent_id'); 30 } 31 32 public function child() 33 { 34 return $this->hasOne(Role::class,'parent_id'); 35 } 36 37 public function users() 38 { 39 return $this->belongsToMany(User::class, 'role_user', 'role_id', 'user_id'); 40 } 41 42 public function tasks(): HasMany 43 { 44 return $this->hasMany(Task::class); 45 } 46 47 public function isUserInThisRole(int $user_id) 48 { 49 $exists = DB::table('role_user') 50 ->where('role_id', $this->id) 51 ->where('user_id', $user_id) 52 ->get(); 53 54 if (count($exists) === 0) { 55 return false; 56 } else { 57 return true; 58 } 59 } 60 61 public function dossiers() 62 { 63 return $this->belongsToMany(Dossier::class, 'role_dossier', 'role_id', 'dossier_id'); 64 } 65 66 public function isInDossier(Dossier $dossier) 67 { 68 $roles = $dossier->roles->toArray(); 69 70 return in_array($this->id, array_column($roles, 'id')); 71 } 72 73 public function documents() 74 { 75 return $this->belongsToMany(Document::class, 'document_role', 'role_id', 'document_id'); 76 } 77 78 public function getActivitylogOptions(): LogOptions 79 { 80 return LogOptions::defaults() 81 ->logOnly([ 82 'name', 83 'description', 84 'can_read_users', 85 'can_write_users', 86 'can_read_configuration', 87 'can_write_configuration', 88 'can_read_dossiers', 89 'can_write_dossiers', 90 'can_read_documents', 91 'can_write_documents', 92 'can_write_tasks', 93 'can_validate_and_approve', 94 'can_read_statistics', 95 ])->logOnlyDirty() 96 ->dontSubmitEmptyLogs(); 97 } 98 }