This snippet of code will callout to the ViaCEP API used to gather address information thru the postal code.
We are using a suffix trigger action, this will create a button on the right side of the input component and will trigger once clicked.
TextInput::make('postal_code') ->label('CEP') ->suffixAction( fn ($state, Closure $set) => Action::make('search-action') ->icon('heroicon-o-search') ->action(function () use ($state, $set) { if (blank($state)) { Filament::notify('danger', 'Digite o CEP para buscar o endereço'); return; } try { $cepData = Http::get("https://viacep.com.br/ws/{$state}/json/") ->throw() ->json(); } catch (RequestException $e) { Filament::notify('danger', 'Erro ao buscar o endereço'); return; } $set('address_neighborhood', $cepData['bairro'] ?? null); $set('address', $cepData['logradouro'] ?? null); $set('city_id', City::where('title', $cepData['localidade'])->first()->id ?? null); $set('state', State::where('letter', $cepData['uf'])->first()->id ?? null); }) ),
Hope you enjoy! Happy coding.
No comments yet…