Weave 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

fomvasss/laravel-dadata

Laravel wrapper for the DaData.ru API, providing convenient access to address suggestions, company details, bank data, and other Russian reference information. Includes configurable API client, facades, and helpers for quick integration.

View on GitHub
Deep Wiki
Context7

Getting Started

  1. Install and publish config

    composer require fomvasss/laravel-dadata
    php artisan vendor:publish --provider="Fomvasss\Dadata\DadataServiceProvider"
    

    Laravel will auto-discover the service provider; the facade/alias is registered from config/app.php if you're on an older skeleton.

  2. Credentials

    Dadata uses two credentials and two base URLs:

    • DADATA_TOKEN – the API key (used by both the clean API and the suggest API).
    • DADATA_SECRET – the secret key (used only by the clean/party/find-by-id API at https://dadata.ru/api/v2/...).
    • The suggest API (https://suggestions.dadata.ru/...) accepts the token alone.

    Put both in .env. A 401 on clean endpoints with a working suggest call is almost always a missing secret, not a bad token.

  3. First use case – clean an address

    use Fomvasss\Dadata\Facades\Dadata;
    
    $result = Dadata::cleanAddress('москва ленина 1');
    // $result['result']         – canonical string
    // $result['geo_lat']        – latitude
    // $result['geo_lon']        – longitude
    // $result['qc']             – quality code (0 = exact, 1 = added, 2 = replaced, 3 = not found)
    
  4. Where to look first

    • config/dadata.php — endpoints, timeouts, default params.
    • src/ — the client class exposes clean*, suggest*, findById, and generic call helpers, one method per Dadata resource (address, phone, name, email, party, bank).
    • The Dadata docs (dadata.ru/api/) map 1:1 onto the method names — read the docs, not the source, for response shapes.

Implementation Patterns

Clean vs. Suggest — pick the right one.

  • Clean = server-side normalization performed on a string you already have (address, phone, name, email, birthdate, passport, vehicle). Requires both token and secret. Synchronous, single record.
  • Suggest = autocomplete for a live search box. Requires only the token. Returns ranked candidates. Call it from the front end or a thin server-side proxy — not from a Laravel request cycle you can afford to slow down.

Wrap the facade in a domain service. Don't sprinkle Dadata::cleanAddress() across controllers. Create App\Services\AddressNormalizer that owns the call, handles empty results, and returns a DTO. This gives you one place to add caching, logging, and test fakes.

Custom validation rule — the highest-value pattern for form submissions:

class DadataAddress implements Rule
{
    public function passes($attribute, $value): bool
    {
        $clean = app(AddressNormalizer::class)->normalize($value);
        return $clean && $clean->qc <= 1 && $clean->country === 'Россия';
    }
}

Cache immutable lookups. By-INN (findById('party', $inn)), by-BIK bank lookups, and by-OGRN lookups change rarely. Wrap in Cache::remember("dadata:party:{$inn}", now()->addDays(7), ...). Never cache suggests — they're query-shaped and user-specific.

Queue non-interactive cleaning. Registering a batch of imported rows, back-filling addresses, or cleaning a CSV should be a queued job. The clean API is fast but rate-limited; a queue with a rateLimited(60, 1) middleware keeps you under the daily quota and out of user-facing latency.

Front-end autocomplete flow. Expose a Laravel route that proxies Dadata::suggestAddress($query, ['count' => 10, 'locations' => [...]]). This keeps the token server-side, lets you scope results by region/city, and lets you log failed lookups. Return a trimmed shape (value, unrestricted_value, data.postal_code`) rather than the full Dadata payload — the full object is huge and bloats the response.

Multi-language / granularity. Pass granularity (e.g. 'city', 'street', 'house') to the suggest call to stop early — it's much faster and cheaper than full-house suggestions. Use the locations filter (ISO or KLADR codes) to constrain to a region.

Testing. The package ultimately issues HTTP requests, so fake the layer:

Http::fake([
    'suggestions.dadata.ru/*' => Http::response(['suggestions' => [...]]),
]);

Or bind a fake client to the container in TestCase::setUp so your service classes are exercised without hitting the network.

Gotchas and Tips

Token vs. secret confusion. The two hosts and two credentials are the #1 source of 401s. Verify both variables are set before debugging anything else. The suggest API will happily work with a token while clean calls fail — that asymmetry misleads people into thinking the package is broken.

value vs. unrestricted_value. In suggest results, value is Dadata's canonical casing; unrestricted_value preserves what the user typed. For display in an autocomplete dropdown, show value. For storing raw input alongside the cleaned form (audit trail), keep both.

Response shape differs by endpoint. Clean endpoints return the standardized fields flatly (result, geo_lat, geo_lon, qc, house, …). Suggest endpoints return { suggestions: [ { value, unrestricted_value, data: {...} } ] }. Don't write generic response handling — treat them as distinct.

Quality codes (qc) are not boolean. qc = 0 exact, 1 added, 2 replaced, 3 not found. qc = 3 still means the HTTP request succeeded — check qc before assuming the address is valid. The package does not throw on a bad match.

Empty suggestions are normal. The suggest API returns suggestions: [] for out-of-scope data (non-Russian addresses, malformed input). Code paths that assume at least one result will crash; always guard for empty($suggestions).

Daily quota, not request-per-second. Dadata meters by daily volume per plan tier. A rateLimited middleware helps with burst protection but won't save you if a batch job cleans 50k rows on a 10k/day plan. Log the daily counter or monitor from the Dadata dashboard.

UTF-8 and Cyrillic. Laravel's default charset is fine, but if you're storing cleaned results, make sure the DB column and connection collation are utf8mb4 — Dadata returns Cyrillic, and utf8 (non-mb4) columns will silently truncate on some ALTER paths.

Empty strings, not nulls. Dadata returns "" for missing fields rather than null. if ($data['geo_lat']) treats "" as falsy — fine — but array_key_exists checks will tell you the field is "present." Normalize to null in your DTO rather than pushing empty strings to Eloquent.

Timeout configuration. The default HTTP timeout in the config is often generous for batch jobs and too long for request cycles. Set a short timeout (e.g. 2–3s) on suggest proxies so a slow Dadata response doesn't hold a web worker — and a long one for queued clean jobs.

Extension points. The clean API has a structure parameter (array of field names) that lets you request only the fields you need — use it to reduce payload size for narrow use cases (e.g. only postal_code + geo_lat + geo_lon). It's exposed through the config or the method options in most wrappers of this package; check the src/ method signature before rolling your own.

No first-party client, so pin versions. This is a community wrapper. Pin the package version in composer.json and add a smoke test that asserts a known address cleans to an expected qc, so a major Dadata API change surfaces in CI rather than in production.

Logging. Wrap the client with a decorator that logs the request type, latency, and qc distribution. When users report "wrong addresses," a log of qc values tells you immediately whether the input is bad (qc=3) or the mapping is bad (qc=1/2 returned but stored incorrectly).

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.
payerurl/telegrambot-crypto-payment-instant-payout
dskripchenko/laravel-hybrid-search
riorizkyrainey/lara-ced
mehedimi/static-vel
zharp/zharp
nonsapiens/bigquery-model-sync
lgu-bayambang-ict-office/lgu-laravel-development-standards
andydefer/laravel-support
se7enxweb/flysystem
lampwick/laravel
jeslage/statamic-emojis
micahdshackelford/rmap-laravel
draftsmaninc/draftsman
square-bit/laravel-volition
himito/laravel-mailman
htinlynn/genius-helper
maco-studios/hephaestus
elmogy/larafast
xeviant/laravel-paystack
gorilladash/laravel-website-sdk