big update base struktur tahap 1
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
<?php
|
||||
|
||||
namespace App\Http\Resources\Wilayah;
|
||||
|
||||
use App\Models\WilayahDesa;
|
||||
use App\Models\WilayahKabupaten;
|
||||
use App\Models\WilayahKecamatan;
|
||||
use App\Models\WilayahProvinsi;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
class WilayahResource extends JsonResource
|
||||
{
|
||||
public function toArray(Request $request): array
|
||||
{
|
||||
$data = [
|
||||
'id' => $this->id,
|
||||
'kode' => $this->kode,
|
||||
'nama' => $this->nama,
|
||||
'tingkat' => match (true) {
|
||||
$this->resource instanceof WilayahDesa => 'desa',
|
||||
$this->resource instanceof WilayahKecamatan => 'kecamatan',
|
||||
$this->resource instanceof WilayahKabupaten => 'kabupaten',
|
||||
$this->resource instanceof WilayahProvinsi => 'provinsi',
|
||||
},
|
||||
'created_at' => $this->created_at,
|
||||
'updated_at' => $this->updated_at,
|
||||
];
|
||||
|
||||
if ($this->resource instanceof WilayahKabupaten) {
|
||||
$data['provinsi_id'] = $this->provinsi_id;
|
||||
$data['provinsi'] = $this->whenLoaded('provinsi', fn () => $this->node($this->provinsi));
|
||||
}
|
||||
|
||||
if ($this->resource instanceof WilayahKecamatan) {
|
||||
$data['kabupaten_id'] = $this->kabupaten_id;
|
||||
$data['kabupaten'] = $this->whenLoaded('kabupaten', fn () => $this->node($this->kabupaten));
|
||||
$data['provinsi'] = $this->when(
|
||||
$this->relationLoaded('kabupaten') && $this->kabupaten?->relationLoaded('provinsi'),
|
||||
fn () => $this->node($this->kabupaten?->provinsi)
|
||||
);
|
||||
}
|
||||
|
||||
if ($this->resource instanceof WilayahDesa) {
|
||||
$data['kecamatan_id'] = $this->kecamatan_id;
|
||||
$data['kecamatan'] = $this->whenLoaded('kecamatan', fn () => $this->node($this->kecamatan));
|
||||
$data['kabupaten'] = $this->when(
|
||||
$this->relationLoaded('kecamatan') && $this->kecamatan?->relationLoaded('kabupaten'),
|
||||
fn () => $this->node($this->kecamatan?->kabupaten)
|
||||
);
|
||||
$data['provinsi'] = $this->when(
|
||||
$this->relationLoaded('kecamatan')
|
||||
&& $this->kecamatan?->relationLoaded('kabupaten')
|
||||
&& $this->kecamatan?->kabupaten?->relationLoaded('provinsi'),
|
||||
fn () => $this->node($this->kecamatan?->kabupaten?->provinsi)
|
||||
);
|
||||
}
|
||||
|
||||
return $data;
|
||||
}
|
||||
|
||||
private function node($wilayah): ?array
|
||||
{
|
||||
return $wilayah ? [
|
||||
'id' => $wilayah->id,
|
||||
'kode' => $wilayah->kode,
|
||||
'nama' => $wilayah->nama,
|
||||
] : null;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user