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

esitchikhin/laravel-dadata

Laravel SDK для DaData.ru (форк movemoveapp/laravel-dadata) с исправлением получения организации по ИНН. Поддерживает PHP 7.3–8.1 и Laravel 7–9. Настройка через .env (DADATA_TOKEN/SECRET/TIMEOUT), публикация конфига через artisan.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require esitchikhin/laravel-dadata
    

    Publish the config file:

    php artisan vendor:publish --provider="Esitchikhin\LaravelDaData\DaDataServiceProvider" --tag="config"
    
  2. Configure .env: Add your DaData API token:

    DADATA_TOKEN=your_api_token_here
    
  3. First Use Case: Validate and correct a phone number:

    use Esitchikhin\LaravelDaData\Facades\DaData;
    
    $phone = DaData::phone()->clean('+7(911)123-45-67');
    // Returns: "+79111234567"
    

Key Facades

  • DaData::phone() – Phone number validation/correction.
  • DaData::address() – Address parsing/suggestions.
  • DaData::suggest() – Autocomplete for addresses, companies, or FIO.
  • DaData::company() – Company details by INN or name.
  • DaData::name() – Name parsing (e.g., extract surname, first name).

Implementation Patterns

Common Workflows

1. Form Validation & Autocomplete

  • Use Case: Enhance user input in forms (e.g., address fields).
  • Pattern:
    // Suggest addresses while typing
    $suggestions = DaData::suggest()->address('ул. Невский, 12', 5); // Top 5 matches
    
    // Clean and validate submitted address
    $cleanedAddress = DaData::address()->clean($request->address);
    

2. Phone Number Handling

  • Use Case: Normalize phone numbers from user submissions.
  • Pattern:
    // Clean raw input
    $cleanPhone = DaData::phone()->clean($request->phone);
    
    // Validate format
    if (!DaData::phone()->isValid($cleanPhone)) {
        return back()->withErrors(['phone' => 'Invalid phone number']);
    }
    

3. Company Data Enrichment

  • Use Case: Fetch company details by INN or name (e.g., for B2B forms).
  • Pattern:
    $company = DaData::company()->byInn('1234567890'); // Returns full company data
    // OR
    $company = DaData::company()->byName('ООО Рога и Копыта');
    

4. Name Parsing

  • Use Case: Extract structured data from full names (e.g., for user profiles).
  • Pattern:
    $parsedName = DaData::name()->parse('Иванов Иван Иванович');
    // Returns:
    // [
    //     'surname' => 'Иванов',
    //     'first_name' => 'Иван',
    //     'patronymic' => 'Иванович',
    // ]
    

5. Integration with Laravel Validation

  • Use Case: Add DaData validation to Laravel’s built-in validation.
  • Pattern:
    use Esitchikhin\LaravelDaData\Rules\Phone;
    
    $request->validate([
        'phone' => ['required', new Phone],
        'address' => ['required', 'dadata_address'], // Custom rule
    ]);
    
  • Custom Rule Example:
    use Esitchikhin\LaravelDaData\Rules\DaDataRule;
    
    class AddressRule extends DaDataRule {
        protected $type = 'address';
    }
    

Integration Tips

  1. Rate Limiting: Cache responses aggressively (e.g., 5-minute TTL for suggestions) to avoid hitting DaData’s rate limits.

    $suggestions = Cache::remember("dadata_suggestions_{$query}", now()->addMinutes(5), function () use ($query) {
        return DaData::suggest()->address($query, 5);
    });
    
  2. Error Handling: Wrap DaData calls in try-catch blocks to handle API errors gracefully:

    try {
        $result = DaData::phone()->clean($phone);
    } catch (\Esitchikhin\LaravelDaData\Exceptions\DaDataException $e) {
        Log::error("DaData API error: " . $e->getMessage());
        return back()->withErrors(['phone' => 'Service unavailable']);
    }
    
  3. Testing: Use the package’s mocking capabilities in tests:

    DaData::shouldReceive('phone()->clean')->andReturn('+79111234567');
    

Gotchas and Tips

Pitfalls

  1. Token Management:

    • The .env token is not encrypted by default. Use Laravel’s env() helper or a secure secrets manager in production.
    • Gotcha: If the token is exposed (e.g., in Git history), regenerate it immediately in the DaData dashboard.
  2. Rate Limits:

  3. INN/Company Lookup:

    • The byInn() method requires a valid 10-digit INN (e.g., 7707085378). Invalid INNs return null.
    • Gotcha: Russian INNs start with 77 (Moscow), 78 (St. Petersburg), etc. Validate the prefix if needed.
  4. Phone Number Formats:

    • DaData expects international format (e.g., +79111234567). Local formats (e.g., 8(911)123-45-67) must be cleaned first.
    • Tip: Use DaData::phone()->clean() before validation.
  5. Address Parsing:

    • DaData’s address suggestions are region-specific. For example, ул. Невский in Moscow (77) differs from St. Petersburg (78).
    • Gotcha: If suggestions are irrelevant, specify a region:
      $suggestions = DaData::suggest()->address('Невский', 5, ['region' => '77']);
      
  6. Deprecated Methods:

    • The original package had a bug in company()->byInn(). This fork fixes it, but always check the changelog for breaking changes.

Debugging Tips

  1. Enable Debug Mode: Set DADATA_DEBUG=true in .env to log raw API responses to storage/logs/dadata.log.

  2. Validate API Responses: Use dd() to inspect responses:

    $response = DaData::suggest()->address('test');
    dd($response->data); // Check structure
    
  3. Common HTTP Errors:

    • 401 Unauthorized: Invalid or missing token. Double-check .env.
    • 429 Too Many Requests: Hit rate limits. Implement caching or reduce request frequency.
    • 500 Server Error: DaData API issue. Check their status page.

Extension Points

  1. Custom DaData Clients: Override the default HTTP client for advanced use cases (e.g., retries, middleware):

    // In config/dadata.php
    'client' => [
        'handler' => \Http\Adapter\Guzzle\Client::class,
        'options' => [
            'timeout' => 10,
            'headers' => [
                'User-Agent' => 'MyApp/1.0',
            ],
        ],
    ],
    
  2. Add New DaData Services: The package follows a modular pattern. To add a new service (e.g., DaData::bank()):

    • Extend the base DaDataService class.
    • Register the new facade in DaDataServiceProvider.
  3. Local Testing: Use DaData’s sandbox for testing without real API calls. Mock responses in tests:

    DaData::shouldReceive('address()->clean')->andReturn(['postal_code' => '123456']);
    
  4. Batch Processing: For bulk operations (e.g., cleaning 1000+ phone numbers), use DaData’s batch API and implement chunking:

    foreach (array_chunk($phones, 100) as $chunk) {
        $cleaned = DaData::phone()->cleanBatch($chunk);
    }
    
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.
besmartand-pro/php-quality-config
sentix/ai-chatbot
terminal42/code-quality-tools
codifyo/ts-generator-bundle
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