PointOfContact.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\SoftDeletes; 8 use Spatie\Activitylog\LogOptions; 9 use Spatie\Activitylog\Traits\LogsActivity; 10 11 class PointOfContact extends Model 12 { 13 use HasFactory, LogsActivity, SoftDeletes; 14 15 protected $table = 'points_of_contact'; 16 17 protected $guarded = []; 18 19 protected $hidden = ['gpg_pass']; 20 21 public function type() 22 { 23 return $this->belongsTo(PointOfContactType::class, 'point_of_contact_type_id'); 24 } 25 26 public function company() 27 { 28 return $this->belongsTo(Company::class); 29 } 30 31 public function laboratory() 32 { 33 return $this->belongsTo(Laboratory::class); 34 } 35 36 public function consultancy() 37 { 38 return $this->belongsTo(Consultancy::class); 39 } 40 41 public static function createAndCheckPrincipal($data = []) 42 { 43 $foreignKey = PointOfContactType::find($data['point_of_contact_type_id'])->name.'_id'; 44 45 if ($data['principal'] === true || $data['principal'] === 1) { 46 $lastPrincipal = PointOfContact::where([ 47 ['principal', true], 48 [$foreignKey, $data[$foreignKey]], 49 ])->first(); 50 51 if ($lastPrincipal) { 52 $lastPrincipal->update([ 53 'principal' => false, 54 ]); 55 } 56 } 57 58 return PointOfContact::create($data); 59 } 60 61 public function updateAndCheckPrincipal($data = []) 62 { 63 $foreignKey = $this->type->name.'_id'; 64 65 if ($data['principal'] === true || $data['principal'] === 1) { 66 $lastPrincipal = PointOfContact::where([ 67 ['principal', true], 68 [$foreignKey, $this->$foreignKey], 69 ])->first(); 70 71 if ($lastPrincipal) { 72 if ($lastPrincipal->id != $this->id) { 73 $lastPrincipal->update([ 74 'principal' => false, 75 ]); 76 } 77 } 78 } 79 80 return $this->update($data); 81 } 82 83 public function getActivitylogOptions(): LogOptions 84 { 85 return LogOptions::defaults() 86 ->logOnly([ 87 'address', 88 'email', 89 'phone', 90 'principal', 91 'point_of_contact_type_id', 92 'type.name', 93 'consultancy_id', 94 'consultancy.name', 95 'laboratory_id', 96 'laboratory.name', 97 'company_id', 98 'company.name', 99 ])->logOnlyDirty() 100 ->dontSubmitEmptyLogs(); 101 } 102 }