jeffersongoncalves/laravel-cep
Laravel package to fetch and validate Brazilian CEP (postal code) data in your app. Provides simple helpers/service to query CEP information and integrate with forms and address lookups, with easy configuration and straightforward usage.
Installation
composer require jeffersongoncalves/laravel-cep
Publish the config file (if needed):
php artisan vendor:publish --provider="JeffersonGoncalves\LaravelCep\CepServiceProvider"
Configuration
Edit config/cep.php to set your preferred provider (e.g., viacep, republicavirtual, or correios). Example:
'provider' => 'viacep',
'timeout' => 10,
'cache' => [
'enabled' => true,
'driver' => 'file',
'minutes' => 60,
],
First Query
Fetch address data for a CEP (e.g., 01001000):
use JeffersonGoncalves\LaravelCep\Facades\Cep;
$address = Cep::find('01001000');
// Returns: [
// 'cep' => '01001000',
// 'logradouro' => 'Praça da Sé',
// 'complemento' => '',
// 'bairro' => 'Sé',
// ...
// ]
Fallback Providers
Configure fallback providers in config/cep.php:
'providers' => [
'viacep' => [
'enabled' => true,
'url' => 'https://viacep.com.br/ws/{cep}/json/',
],
'republicavirtual' => [
'enabled' => false,
'url' => 'https://www.republicavirtual.com.br/web_cep.php?cep={cep}&formato=json',
],
],
$cep = '01310100';
$data = Cep::find($cep);
// Validate response
if ($data->success()) {
$street = $data->logradouro;
$district = $data->bairro;
$city = $data->localidade;
$state = $data->uf;
}
Enable caching in config/cep.php to avoid repeated API calls:
'cache' => [
'enabled' => true,
'driver' => 'redis', // or 'file', 'database'
'minutes' => 1440, // 24 hours
],
Clear cache manually if needed:
php artisan cache:clear
Check the active provider and handle provider-specific quirks:
$provider = config('cep.provider');
if ($provider === 'viacep') {
// Handle ViaCEP-specific fields (e.g., 'ibge')
}
Use Laravel's collect() for batch CEP validation:
$ceps = ['01001000', '04534020', '22011000'];
$results = collect($ceps)->map(fn($cep) => Cep::find($cep));
Add a CEP-based scope to a User or Address model:
namespace App\Models;
use JeffersonGoncalves\LaravelCep\Facades\Cep;
use Illuminate\Database\Eloquent\Builder;
class Address extends Model
{
public function scopeValidCep(Builder $query, string $cep)
{
$data = Cep::find($cep);
return $data->success() ? $query->where('cep', $cep) : $query;
}
}
Usage:
$address = Address::validCep('01001000')->first();
Validate CEP format and existence:
use Illuminate\Support\Facades\Validator;
$validator = Validator::make($request->all(), [
'cep' => [
'required',
'string',
'size:8',
function ($attribute, $value, $fail) {
$data = Cep::find($value);
if (!$data->success()) {
$fail('CEP inválido ou inexistente.');
}
},
],
]);
Implement middleware to throttle CEP requests:
namespace App\Http\Middleware;
use Closure;
use JeffersonGoncalves\LaravelCep\Facades\Cep;
use Illuminate\Http\Request;
class ThrottleCepRequests
{
public function handle(Request $request, Closure $next)
{
if ($request->is('api/cep/*')) {
$limit = config('cep.rate_limit', 10);
if (Cep::getRequestCount() >= $limit) {
return response()->json(['error' => 'Limite de consultas excedido.'], 429);
}
}
return $next($request);
}
}
Environment-Specific Providers Use environment variables to switch providers:
'provider' => env('CEP_PROVIDER', 'viacep'),
Logging Failed Requests Extend the package to log failed CEP lookups:
Cep::extend(function ($app) {
$app->resolving('cep', function ($cep, $app) {
$cep->setLogger(app(\Illuminate\Log\Logger::class));
});
});
Fallback Logic
Implement a fallback chain in AppServiceProvider:
public function boot()
{
Cep::extend(function ($app) {
$app->afterResolving('cep', function ($cep) {
if (!$cep->success() && config('cep.fallback.enabled')) {
$fallbackProvider = config('cep.fallback.provider');
$cep->setProvider($fallbackProvider)->findAgain();
}
});
});
}
CEP Format Validation
01001000, not 01.001-000).$cleanCep = preg_replace('/[^0-9]/', '', $request->cep);
Provider-Specific Fields
viacep returns ibge, while correios may return municipio.$data->city = $data->localidade ?? $data->municipio ?? null;
Rate Limits
Cache Invalidation
cache:forget route or manual invalidation:
Cep::forgetCache('01001000');
HTTPS Requirements
republicavirtual) may fail on HTTP.https://.Timeouts
config('cep.timeout') (default: 10 seconds).Provider Unavailability
Cep::setProvider('viacep')->find('01001000')->retry(3);
Enable Debug Mode
Set config('cep.debug', true) to log raw API responses:
'debug' => env('CEP_DEBUG', false),
Check HTTP Status Codes
Inspect the response object for errors:
$data = Cep::find('01001000');
if ($data->response->status() === 404) {
// CEP not found
}
Mock Providers for Testing Use Laravel's HTTP mocking:
$this->mock(\JeffersonGoncalves\LaravelCep\Contracts\CepProvider::class, function ($mock) {
$mock->shouldReceive('find')
->once()
How can I help you explore Laravel packages today?