Installation
composer require unforgivencl/larachileanlaw:dev-master
Add the service provider to config/app.php under providers:
Unforgivencl\LaraChileanLaw\LaraChileanLawServiceProvider::class,
Optionally, add the facade alias:
'LaraChileanLaw' => Unforgivencl\LaraChileanLaw\Facades\LaraChileanLaw::class,
First Use Case Fetch the latest 5 published laws:
use LaraChileanLaw;
$laws = LaraChileanLaw::law()->paginate(5)->getLatestPublished()->fetch();
Querying Laws Chain methods for granular control:
// Get laws paginated with content filter
$laws = LaraChileanLaw::law()
->paginate(10)
->content('aborto')
->getByContent()
->fetch();
// Get a specific law by BCN (e.g., "1")
$law = LaraChileanLaw::law()
->number('1')
->getLatestSpecific()
->fetch();
Integration with Laravel Ecosystem
$response = LaraChileanLaw::law()->fetch(); // Returns JSON
$cachedLaws = Cache::remember('latest_laws', now()->addHours(1), function () {
return LaraChileanLaw::law()->paginate(5)->getLatestPublished()->fetch();
});
Error Handling
Wrap calls in try-catch for API failures:
try {
$law = LaraChileanLaw::law()->number('999')->fetch();
} catch (\Exception $e) {
Log::error("Chilean Law API Error: " . $e->getMessage());
return response()->json(['error' => 'Failed to fetch law'], 500);
}
Inconsistent XML Structure
leychile.cl API returns inconsistent XML. Validate responses:
if (!isset($response['data'])) {
throw new \RuntimeException("Unexpected API response format");
}
Rate Limiting
Facade vs. Direct Usage
LaraChileanLaw::law()) is convenient but less testable. For tests, inject the service directly:
$this->app->bind(\Unforgivencl\LaraChileanLaw\Contracts\ChileanLaw::class, function () {
return new \Unforgivencl\LaraChileanLaw\ChileanLawClient();
});
Log Raw Responses: Inspect XML/JSON for debugging:
$rawResponse = LaraChileanLaw::law()->number('1')->fetch();
Log::debug("Raw API Response:", ['response' => $rawResponse]);
Check for Deprecations: The package is in early development. Verify compatibility with leychile.cl updates.
Custom Endpoints Extend the base client to support undocumented endpoints:
// In a service class
public function getDraftLaws() {
return $this->client->request('GET', '/api/drafts');
}
Response Transformers
Override JSON conversion logic in app/Providers/AppServiceProvider:
public function boot() {
LaraChileanLaw::extend(function ($client) {
$client->setTransformer(function ($xml) {
return json_decode(json_encode(simplexml_load_string($xml)), true);
});
});
}
Testing Mock the API client in tests:
$mock = Mockery::mock(\Unforgivencl\LaraChileanLaw\Contracts\ChileanLaw::class);
$mock->shouldReceive('fetch')->andReturn(['data' => []]);
$this->app->instance(\Unforgivencl\LaraChileanLaw\Contracts\ChileanLaw::class, $mock);
How can I help you explore Laravel packages today?