layout: default title: Usage nav_order: 4 —

Usage

Table of contents

  1. Querying Data
    1. Find Locations by Postcode
    2. Find Postcode with Full Hierarchy
    3. Find All Postcodes in a State
    4. Search Locations by Name
  2. Updating Data
  3. Using in DatabaseSeeder

Querying Data

Find Locations by Postcode

use Ajangsupardi\PostcodeMy\Models\Location;

$locations = Location::whereHas('postcode', function ($query) {
    $query->where('postcode', '50000');
})->get();

Find Postcode with Full Hierarchy

use Ajangsupardi\PostcodeMy\Models\Postcode;

$postcode = Postcode::with('state', 'locations')
    ->where('postcode', '50000')
    ->first();

Find All Postcodes in a State

use Ajangsupardi\PostcodeMy\Models\State;

$state = State::where('code', 'KL')->first();
$postcodes = $state->postcodes;

Search Locations by Name

$locations = Location::name('Jalan')->get();

Updating Data

If you need the latest postcode data from Pos Malaysia:

php artisan postcode:download
php artisan postcode:seed

The download command queries the Pos Malaysia API for each postcode (00000–99999). This takes approximately 30 minutes.

After updating, bump the data version in config/postcode.php:

'data_version' => '1.1.0',
'data_updated_at' => '2026-12-31',

Using in DatabaseSeeder

<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Ajangsupardi\PostcodeMy\Database\Seeders\PostcodeSeeder;

class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        $this->call([
            PostcodeSeeder::class,
        ]);
    }
}