Postcode lookup
lookup() returns the addresses at a postcode, or the API's closest matching postcodes when it is not found. It never throws for an unknown postcode.
use IdealPostcodes\IdealPostcodes;
$client = IdealPostcodes::client('ak_test');
$lookup = $client->lookup('BR8 7RE');
if ($lookup->found) {
foreach ($lookup->addresses as $address) {
echo $address->line1, ', ', $address->postTown, ', ', $address->postcode, PHP_EOL;
}
} else {
echo 'Did you mean: ', implode(', ', $lookup->suggestions), PHP_EOL;
}
What does lookup() return?
A PostcodeLookup object.
| Property | Contents |
|---|---|
found | true when the postcode exists |
addresses | The addresses on this page, as AddressListItem objects. [] when not found |
suggestions | Up to five closest matching postcodes when not found, otherwise [] |
total | Addresses at the postcode across all pages. 0 when not found |
An unfound postcode costs no lookup. Other errors, such as an invalid key or an empty balance, still throw ApiException. See error handling.
When should I use postcodes() instead?
postcodes() returns the full PostcodeResponse, with page, limit and total, and throws ApiException with code 4040 when the postcode is not found. Use it when you page through a large postcode or want the raw response.
$response = $client->postcodes('BR8 7RE', ['page' => 0]);
echo $response->total, ' addresses, ', count($response->result), ' on this page', PHP_EOL;
How do I page through a Multiple Residence postcode?
A small number of postcodes return more than 100 premises. The API returns 100 addresses per page, so pass page until you have total addresses.
$page = 0;
$addresses = [];
do {
$response = $client->postcodes('CV4 7AL', ['page' => $page++]);
array_push($addresses, ...$response->result);
} while (count($addresses) < $response->total);
How do I limit the fields returned?
Pass filter with the fields you need, as a comma separated string or a list. Fields left out of the response come back as empty strings on the address object.
$lookup = $client->lookup('BR8 7RE', ['filter' => ['line_1', 'line_2', 'post_town', 'postcode']]);
Every parameter is on the postcodes() reference page.