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 Dadata Laravel Package

movemoveapp/laravel-dadata

View on GitHub
Deep Wiki
Context7
## Getting Started
Install via Composer:
```bash
composer require movemoveapp/laravel-dadata

Publish the configuration file (if needed) with:

php artisan vendor:publish --provider="Movemove\Dadata\DadataServiceProvider"

Register the service provider in config/app.php under providers (if not auto-discovered). First use case: Fetching address suggestions:

use Movemove\Dadata\Dadata;

$suggestions = Dadata::address()->suggest('Москва');

Implementation Patterns

Core Workflows

  1. Service Initialization Configure the API token in .env:

    DADATA_TOKEN=your_api_token_here
    

    Or set it programmatically:

    Dadata::setToken('your_api_token');
    
  2. Common API Calls

    • Suggestions: Use Dadata::[entity]()->suggest('query') (e.g., address, party, suggest).
    • Validation: Use Dadata::[entity]()->validate($data) (e.g., address, party).
    • Cleaning: Use Dadata::[entity]()->clean($data) (e.g., address, party).
  3. Batch Processing For bulk operations, leverage Laravel’s collections or chunking:

    $data = collect([...]);
    $results = $data->map(fn($item) => Dadata::address()->clean($item));
    
  4. Error Handling Wrap API calls in try-catch blocks to handle Movemove\Dadata\Exceptions\DadataException:

    try {
        $result = Dadata::address()->suggest('Invalid Query');
    } catch (\Movemove\Dadata\Exceptions\DadataException $e) {
        Log::error($e->getMessage());
    }
    

Integration Tips

  • Caching: Cache responses for frequently used queries (e.g., address suggestions) using Laravel’s cache:
    $cacheKey = 'dadata_address_suggestions_' . md5('Москва');
    $suggestions = Cache::remember($cacheKey, now()->addHours(1), function () {
        return Dadata::address()->suggest('Москва');
    });
    
  • Queue Jobs: Offload heavy validation/cleaning tasks to queues:
    Dadata::address()->clean($data)->then(function ($result) {
        // Process result
    })->otherwise(function ($exception) {
        // Handle failure
    });
    

Gotchas and Tips

Pitfalls

  1. Token Management

    • Ensure DADATA_TOKEN is set in .env or configured programmatically. Missing tokens cause DadataException.
    • Avoid hardcoding tokens in source files.
  2. Rate Limits

    • Dadata API has rate limits. Monitor usage and implement retries with exponential backoff:
      use Symfony\Component\Process\Exception\ProcessFailedException;
      
      try {
          $result = Dadata::address()->suggest('Query');
      } catch (ProcessFailedException $e) {
          if (str_contains($e->getMessage(), 'rate limit')) {
              sleep(2); // Retry after delay
              retry();
          }
      }
      
  3. Data Formatting

    • Input data must match Dadata’s expected format (e.g., address requires street, house, etc.). Invalid data triggers validation errors.
  4. PHP 8 / Laravel 9 Compatibility

    • This release drops support for older PHP/Laravel versions. Ensure your project meets the requirements (PHP 8.x, Laravel 9+).

Debugging

  • Enable Debug Mode Set DADATA_DEBUG=true in .env to log raw API responses for debugging:

    DADATA_DEBUG=true
    

    Check logs in storage/logs/laravel.log.

  • Test Locally Use Dadata’s sandbox for testing without hitting rate limits.

Extension Points

  1. Custom Entities Extend the package by creating custom entities (e.g., Dadata::customEntity()) by publishing and modifying the config:

    // config/dadata.php
    'entities' => [
        'custom' => [
            'endpoint' => 'custom/v1',
            'methods' => ['suggest', 'clean'],
        ],
    ];
    
  2. Middleware Add middleware to the DadataServiceProvider to log API calls or transform responses:

    public function boot()
    {
        Dadata::extend(function ($dadata) {
            $dadata->before(function ($request) {
                Log::info('Dadata API call', $request->all());
            });
        });
    }
    
  3. Testing Mock the Dadata client in tests using Laravel’s HTTP testing:

    $response = Http::fake([
        'api.dadata.ru/*' => Http::response(['result' => true], 200),
    ]);
    $result = Dadata::address()->suggest('Test');
    $response->assertSent();
    

NO_UPDATE_NEEDED would **not** apply here due to the breaking changes (PHP 8/Laravel 9 requirement) and new compatibility features.
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.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
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