95 lines
2.4 KiB
PHP
95 lines
2.4 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
|
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
|
use Illuminate\Foundation\Auth\User as Authenticatable;
|
|
use App\Enums\Role;
|
|
use Illuminate\Notifications\Notifiable;
|
|
use Illuminate\Database\Eloquent\SoftDeletes;
|
|
use Illuminate\Database\Eloquent\Relations\HasOne;
|
|
use Illuminate\Database\Eloquent\Relations\HasMany;
|
|
use Laravel\Sanctum\HasApiTokens;
|
|
|
|
use App\Models\Konfigurasi\KoordinatorKomoditas;
|
|
use App\Models\Pertanian\Petani;
|
|
|
|
class User extends Authenticatable
|
|
{
|
|
use HasFactory, Notifiable, HasApiTokens, SoftDeletes;
|
|
|
|
protected $fillable = [
|
|
'name',
|
|
'email',
|
|
'password',
|
|
'email_verified_at',
|
|
'role',
|
|
'username',
|
|
'uid',
|
|
'status'
|
|
];
|
|
|
|
protected $hidden = [
|
|
'password',
|
|
'remember_token',
|
|
];
|
|
|
|
protected function casts(): array
|
|
{
|
|
return [
|
|
'email_verified_at' => 'datetime',
|
|
'password' => 'hashed',
|
|
'role' => Role::class,
|
|
];
|
|
}
|
|
|
|
public function profile(): HasOne
|
|
{
|
|
return $this->hasOne(\App\Models\Profile::class);
|
|
}
|
|
|
|
public function petaniDibuat(): HasMany
|
|
{
|
|
return $this->hasMany(Petani::class, 'created_by');
|
|
}
|
|
|
|
protected static function booted(): void
|
|
{
|
|
static::deleting(function (User $user) {
|
|
if ($user->isForceDeleting()) {
|
|
return;
|
|
}
|
|
|
|
$user->koordinatorKomoditas()->get()->each->delete();
|
|
});
|
|
}
|
|
|
|
public function koordinatorKomoditas(): HasMany
|
|
{
|
|
return $this->hasMany(KoordinatorKomoditas::class, 'user_id');
|
|
}
|
|
|
|
public function isKoordinator(): bool
|
|
{
|
|
return $this->role === Role::KOORDINATOR;
|
|
}
|
|
|
|
// Daftar id komoditas yang ditugaskan ke koordinator ini.
|
|
public function komoditasKoordinatorIds(): array
|
|
{
|
|
return $this->koordinatorKomoditas()->pluck('komoditas_id')->all();
|
|
}
|
|
|
|
// Koordinator hanya boleh mengakses petani dengan komoditas utama yang ditugaskan.
|
|
// Role lain tidak dibatasi di sini (aturannya tetap di masing-masing controller).
|
|
public function bolehAksesPetani(Petani $petani): bool
|
|
{
|
|
if (! $this->isKoordinator()) {
|
|
return true;
|
|
}
|
|
|
|
return in_array($petani->komoditas_id, $this->komoditasKoordinatorIds());
|
|
}
|
|
}
|