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

Bpost Address Webservice Laravel Package

spatie/bpost-address-webservice

PHP wrapper for bpost’s Address Webservice. Create Address objects and validate Belgian addresses, receiving normalized fields plus warnings/errors/issue lists you can inspect and act on. Useful for checkout forms and address cleanup.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require spatie/bpost-address-webservice
    

    Publish the config (if needed) with:

    php artisan vendor:publish --provider="Spatie\BpostAddressWebservice\BpostAddressWebserviceServiceProvider"
    
  2. First Use Case: Validate a Belgian address in a form submission or API endpoint:

    use Spatie\BpostAddressWebservice\Address;
    use Spatie\BpostAddressWebservice\AddressValidator;
    
    $address = Address::create([
        'streetName' => 'Samberstraat',
        'streetNumber' => '69',
        'postalCode' => '2060',
        'municipalityName' => 'Antwerpen',
        'country' => 'BELGIE',
    ]);
    
    $validator = AddressValidator::create();
    $validatedAddress = $validator->validate($address);
    
    if ($validatedAddress->hasErrors()) {
        // Handle errors (e.g., redirect with flash message or return API error)
    }
    
  3. Where to Look First:

    • Config: config/bpost-address-webservice.php (API key, endpoint, timeout).
    • Address Model: Spatie\BpostAddressWebservice\Address (required fields, validation rules).
    • Validator: Spatie\BpostAddressWebservice\AddressValidator (methods like validate(), hasErrors()).

Implementation Patterns

Common Workflows

  1. Form Validation (Laravel Blade):

    // In a controller
    public function store(Request $request) {
        $address = Address::create($request->validated());
        $validated = AddressValidator::create()->validate($address);
    
        if ($validated->hasErrors()) {
            return back()->withErrors($validated->errors());
        }
        // Proceed with saving...
    }
    
  2. API Endpoint:

    public function validateAddress(Request $request) {
        $address = Address::create($request->all());
        $validated = AddressValidator::create()->validate($address);
    
        return response()->json([
            'valid' => !$validated->hasErrors(),
            'issues' => $validated->issues(),
        ]);
    }
    
  3. Bulk Validation:

    $addresses = collect([...]); // Array of Address models
    $validated = $addresses->map(fn ($addr) => AddressValidator::create()->validate($addr));
    
  4. Autocomplete Integration: Use the AddressSuggestionFinder to fetch suggestions for street names or municipalities:

    $finder = AddressSuggestionFinder::create();
    $suggestions = $finder->findSuggestions('Antw');
    

Integration Tips

  • Laravel Validation: Extend Laravel’s validator to use this package:
    use Spatie\BpostAddressWebservice\Rules\ValidBpostAddress;
    
    $request->validate([
        'address' => ['required', new ValidBpostAddress],
    ]);
    
  • Caching: Cache validated addresses or suggestions to reduce API calls:
    Cache::remember("bpost_{$postalCode}", now()->addHours(1), fn() => $validator->validate($address));
    
  • Queue Jobs: Offload validation to a queue for long-running processes:
    ValidateBpostAddress::dispatch($address)->onQueue('bpost');
    
  • Testing: Mock the AddressValidator in tests:
    $mockValidator = Mockery::mock(AddressValidator::class);
    $mockValidator->shouldReceive('validate')->andReturn($validatedAddress);
    

Gotchas and Tips

Pitfalls

  1. API Key Requirements:

    • The package requires a Bpost API key (configured in .env or config/bpost-address-webservice.php).
    • Gotcha: Forgetting to set the key will throw Spatie\BpostAddressWebservice\Exceptions\MissingApiKey.
    • Fix: Add to .env:
      BPOST_ADDRESS_WEBSERVICE_API_KEY=your_key_here
      
  2. Rate Limiting:

    • Bpost’s API has rate limits (e.g., 10 requests/minute).
    • Gotcha: Bulk operations may hit limits unexpectedly.
    • Fix: Implement exponential backoff or queue delays:
      try {
          $validator->validate($address);
      } catch (RateLimitExceededException $e) {
          sleep(10); // Wait and retry
          retry();
      }
      
  3. Field Requirements:

    • Gotcha: Missing required fields (e.g., country must be "BELGIE") will fail silently or return generic errors.
    • Fix: Validate fields before calling the API:
      if (!$address->isValid()) {
          throw new \InvalidArgumentException('Address is missing required fields.');
      }
      
  4. Municipality Name Sensitivity:

    • Belgian municipality names are case-sensitive (e.g., "Antwerpen""ANTWERPEN").
    • Fix: Normalize input:
      $address->municipalityName = Str::upper($request->municipalityName);
      
  5. Box Number Handling:

    • Gotcha: The boxNumber field is optional but must be omitted if not applicable (e.g., no box for a street address).
    • Fix: Set to null if unused:
      $address->boxNumber = $request->boxNumber ?? null;
      

Debugging Tips

  1. Enable Debug Mode: Set debug to true in config to log raw API responses:

    'debug' => env('BPOST_DEBUG', false),
    

    Check logs in storage/logs/laravel.log.

  2. HTTP Client Errors:

    • Wrap calls in a try-catch to handle:
      • ConnectionException: Network issues.
      • ServerException: Bpost API downtime.
      • DecodingException: Invalid response format.
    • Example:
      try {
          $validated = $validator->validate($address);
      } catch (\Exception $e) {
          report($e); // Log to Sentry/Laravel
          throw new \RuntimeException('Failed to validate address: ' . $e->getMessage());
      }
      
  3. Testing Locally:

    • Use the AddressValidator’s setClient() method to mock HTTP calls in tests:
      $validator->setClient($mockClient);
      

Extension Points

  1. Custom Validation Logic: Extend the Address model to add business rules:

    class CustomAddress extends Address {
        public function rules() {
            return array_merge(parent::rules(), [
                'streetName' => ['required', 'max:100'],
            ]);
        }
    }
    
  2. Webhook Integration: Listen for Bpost API webhooks (e.g., address changes) by extending the WebhookHandler:

    class CustomWebhookHandler extends WebhookHandler {
        public function handle(array $payload) {
            // Custom logic for payloads like 'address_updated'
        }
    }
    
  3. Fallback for Offline Use: Implement a fallback validator for when the Bpost API is unavailable:

    class FallbackValidator {
        public function validate(Address $address) {
            // Simple regex checks or local DB lookup
        }
    }
    
  4. Localization: Override error/warning messages in language files:

    // resources/lang/en/bpost.php
    return [
        'errors' => [
            'invalid_postal_code' => 'The postal code :code is invalid for Belgium.',
        ],
    ];
    
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.
davejamesmiller/laravel-breadcrumbs
artisanry/parsedown
christhompsontldr/phpsdk
enqueue/dsn
bunny/bunny
enqueue/test
enqueue/null
enqueue/amqp-tools
milesj/emojibase
bower-asset/punycode
bower-asset/inputmask
bower-asset/jquery
bower-asset/yii2-pjax
laravel/nova
spatie/laravel-mailcoach
spatie/laravel-superseeder
laravel/liferaft
nst/json-test-suite
danielmiessler/sec-lists
jackalope/jackalope-transport