File: /var/www/matriculas_api_dev/app/Repositories/RegionRepository.php
<?php
namespace App\Repositories;
use App\Models\Region;
use Exception;
class RegionRepository
{
public function getAll()
{
$registers = Region::where('status', true);
return $registers->orderBy('region', 'asc')->get();
}
public function getRegions()
{
$registers = Region::where('status', true)
// Trae las comunas asociadas a cada región
->with('communes')
// Cuenta la cantidad de comunas asociadas a cada región
->withCount('communes')
->get();
return $registers;
}
public function getById($id)
{
$register = Region::where('id', $id)->first();
if (!$register) {
throw new Exception("Región no existe o fue eliminada", 404);
}
return $register;
}
public function getByCode($code, $id = null)
{
$query = Region::where('status', true)->where('code', strLower($code));
if ($id > 0) {
$query->where('id', '!=', $id);
}
$register = $query->first();
if (!$register) {
return false;
}
return $register;
}
public function getByName($region, $id = null)
{
$query = Region::where('region', strUpper($region));
if ($id > 0) {
$query->where('id', '!=', $id);
}
$register = $query->first();
if (!$register) {
return false;
}
return $register;
}
public function create($data)
{
return Region::create([
'code' => $data->code,
'region' => $data->region,
'long_name' => $data->long_name,
'created_at' => now(),
'updated_at' => now(),
]);
}
public function update($register, $data)
{
$register->code = $data->code;
$register->region = $data->region;
$register->long_name = $data->long_name;
$register->updated_at = now();
if ($register->save()) {
return true;
}
return false;
}
}