Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Cep Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation

    composer require jeffersongoncalves/laravel-cep
    

    Publish the config file (if needed):

    php artisan vendor:publish --provider="JeffersonGoncalves\LaravelCep\CepServiceProvider"
    
  2. 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,
    ],
    
  3. 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é',
    //   ...
    // ]
    
  4. 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',
        ],
    ],
    

Implementation Patterns

Common Workflows

1. Basic Address Lookup

$cep = '01310100';
$data = Cep::find($cep);

// Validate response
if ($data->success()) {
    $street = $data->logradouro;
    $district = $data->bairro;
    $city = $data->localidade;
    $state = $data->uf;
}

2. Caching Responses

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

3. Provider-Specific Logic

Check the active provider and handle provider-specific quirks:

$provider = config('cep.provider');
if ($provider === 'viacep') {
    // Handle ViaCEP-specific fields (e.g., 'ibge')
}

4. Batch Processing

Use Laravel's collect() for batch CEP validation:

$ceps = ['01001000', '04534020', '22011000'];
$results = collect($ceps)->map(fn($cep) => Cep::find($cep));

5. Integration with Eloquent

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();

6. Form Validation

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.');
            }
        },
    ],
]);

7. API Rate Limiting

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);
    }
}

Integration Tips

  • 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();
                }
            });
        });
    }
    

Gotchas and Tips

Pitfalls

  1. CEP Format Validation

    • The package expects only digits (e.g., 01001000, not 01.001-000).
    • Fix: Sanitize input with:
      $cleanCep = preg_replace('/[^0-9]/', '', $request->cep);
      
  2. Provider-Specific Fields

    • viacep returns ibge, while correios may return municipio.
    • Tip: Normalize fields post-query:
      $data->city = $data->localidade ?? $data->municipio ?? null;
      
  3. Rate Limits

    • Free providers (e.g., ViaCEP) may throttle excessive requests.
    • Solution: Implement caching or queue delayed requests.
  4. Cache Invalidation

    • If addresses change (e.g., new streets), cached data may stale.
    • Workaround: Add a cache:forget route or manual invalidation:
      Cep::forgetCache('01001000');
      
  5. HTTPS Requirements

    • Some providers (e.g., republicavirtual) may fail on HTTP.
    • Fix: Ensure your server uses HTTPS or configure the provider URL to use https://.
  6. Timeouts

    • Slow providers may cause timeouts. Adjust config('cep.timeout') (default: 10 seconds).
  7. Provider Unavailability

    • If a provider's API is down, the package will fail silently.
    • Tip: Enable fallback providers or add retry logic:
      Cep::setProvider('viacep')->find('01001000')->retry(3);
      

Debugging Tips

  1. Enable Debug Mode Set config('cep.debug', true) to log raw API responses:

    'debug' => env('CEP_DEBUG', false),
    
  2. Check HTTP Status Codes Inspect the response object for errors:

    $data = Cep::find('01001000');
    if ($data->response->status() === 404) {
        // CEP not found
    }
    
  3. Mock Providers for Testing Use Laravel's HTTP mocking:

    $this->mock(\JeffersonGoncalves\LaravelCep\Contracts\CepProvider::class, function ($mock) {
        $mock->shouldReceive('find')
             ->once()
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
cadot.eu/make
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky