Files
Verde-Web/app/Http/Controllers/Api/V1/Geo/BarangayController.php

49 lines
1.9 KiB
PHP

<?php
namespace App\Http\Controllers\Api\V1\Geo;
use App\Http\Controllers\Api\V1\ApiController;
use App\Http\Resources\BarangayResource;
use App\Models\Barangay;
use App\Models\Tenant;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
class BarangayController extends ApiController
{
public function __invoke(Request $request): JsonResponse
{
$request->validate([
'city' => ['nullable', 'string', 'max:32'],
'city_id' => ['nullable', 'integer'],
'q' => ['nullable', 'string', 'max:100'],
]);
$user = $request->user();
$barangays = Barangay::with('cityMunicipality')
->when($request->filled('tenant_id'), function ($q) use ($request) {
$tenant = Tenant::find($request->integer('tenant_id'));
if ($tenant) {
$q->where('city_municipality_id', $tenant->city_municipality_id);
}
})
->when(!$request->filled('tenant_id') && $user && $user->tenant_id, function ($q) use ($user) {
$tenant = $user->tenant ?: Tenant::find($user->tenant_id);
if ($tenant) {
$q->where('city_municipality_id', $tenant->city_municipality_id);
}
})
->when($request->filled('city'), function ($q) use ($request) {
$q->whereHas('cityMunicipality', fn ($c) => $c->where('psgc_code', $request->string('city'))
->orWhere('code', $request->string('city')));
})
->when($request->filled('city_id'), fn ($q) => $q->where('city_municipality_id', $request->integer('city_id')))
->when($request->filled('q'), fn ($q) => $q->where('name', 'like', '%'.$request->string('q').'%'))
->orderBy('name')
->limit(500)
->get();
return $this->ok(BarangayResource::collection($barangays));
}
}