PHPackages                             pk305/cbk-forex - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Utility &amp; Helpers](/categories/utility)
4. /
5. pk305/cbk-forex

ActiveLibrary[Utility &amp; Helpers](/categories/utility)

pk305/cbk-forex
===============

A Laravel package that fetches and stores Central Bank of Kenya (CBK) foreign exchange rates with daily auto-updates.

v1.0.1(1mo ago)048MITPHPPHP ^8.1

Since Apr 23Pushed 1mo agoCompare

[ Source](https://github.com/pk305/cbk-forex)[ Packagist](https://packagist.org/packages/pk305/cbk-forex)[ RSS](/packages/pk305-cbk-forex/feed)WikiDiscussions main Synced 1w ago

READMEChangelogDependencies (8)Versions (3)Used By (0)

CBK Forex — Laravel Package
===========================

[](#cbk-forex--laravel-package)

A Laravel package that fetches **Central Bank of Kenya (CBK) foreign exchange rates** daily and stores them in your database, with a clean API for querying rates by date, currency, or history.

---

Features
--------

[](#features)

- ✅ Fetches live rates from the [CBK official data endpoint](https://www.centralbank.go.ke/forex-exchange-rates/)
- ✅ Stores rates with ISO currency codes and human-readable names
- ✅ **Daily auto-scheduling** via Laravel's task scheduler — no cron setup needed
- ✅ Artisan command for manual fetches and CI pipelines
- ✅ `upsert` logic — re-running never creates duplicates
- ✅ Eloquent model with helpful query scopes
- ✅ Optional API endpoints (REST)
- ✅ Optional pruning of old records
- ✅ Configurable via `.env` or published config file

---

Requirements
------------

[](#requirements)

DependencyVersionPHP^8.1Laravel10, 11, or 12---

Installation
------------

[](#installation)

```
composer require pk305/cbk-forex
```

### Publish the config (optional)

[](#publish-the-config-optional)

```
php artisan vendor:publish --tag=cbk-forex-config
```

### Run the migration

[](#run-the-migration)

```
php artisan migrate
```

---

Scheduling (Daily Auto-Fetch)
-----------------------------

[](#scheduling-daily-auto-fetch)

The package **automatically registers** a daily scheduled command. All you need is a working Laravel scheduler. If you haven't set it up yet, add this single cron entry to your server:

```
* * * * * cd /path-to-your-project && php artisan schedule:run >> /dev/null 2>&1
```

By default the fetch runs at **14:00 (2 PM) EAT** — after CBK typically publishes rates. Change the time in your `.env`:

```
CBK_FOREX_FETCH_TIME=14:00
```

---

Manual Fetch (Artisan)
----------------------

[](#manual-fetch-artisan)

```
# Fetch and store latest rates
php artisan cbk-forex:fetch

# Fetch + prune old records
php artisan cbk-forex:fetch --prune
```

---

Environment Variables
---------------------

[](#environment-variables)

```
# CBK data endpoint (rarely needs changing)
CBK_FOREX_URL=https://www.centralbank.go.ke/wp-admin/admin-ajax.php?action=get_wdtable&table_id=193

# HTTP timeouts (seconds)
CBK_FOREX_TIMEOUT=30
CBK_FOREX_CONNECT_TIMEOUT=10

# SSL verification (set to false only for local dev)
CBK_FOREX_VERIFY_SSL=true

# Daily fetch time (HH:MM, 24hr)
CBK_FOREX_FETCH_TIME=14:00

# Database table name
CBK_FOREX_TABLE=cbk_exchange_rates

# Pruning (optional)
CBK_FOREX_PRUNE=false
CBK_FOREX_KEEP_DAYS=365
```

---

Usage
-----

[](#usage)

### Using the Facade

[](#using-the-facade)

```
use Pk305\CbkForex\Facades\CbkForex;

// Manually trigger a fetch
$result = CbkForex::fetchAndStore();
// => ['fetched' => 21, 'saved' => 21, 'skipped' => 0, 'date' => '2026-04-23']

// Get the latest available rates (keyed by ISO code)
$rates = CbkForex::latestRates();
$usdRate = $rates['USD']->rate; // e.g. 129.21

// Get rates for a specific date
$rates = CbkForex::ratesForDate('2026-04-22');

// Get 30-day history for a currency
$history = CbkForex::historyForCurrency('USD', 30);
```

### Using the Eloquent Model Directly

[](#using-the-eloquent-model-directly)

```
use Pk305\CbkForex\Models\ExchangeRate;

// Today's rates
ExchangeRate::forDate()->get();

// Specific date
ExchangeRate::forDate('2026-04-22')->get();

// A single currency
ExchangeRate::forCurrency('USD')->forDate()->first();

// Quick rate lookup
$rate = ExchangeRate::getRate('EUR'); // float or null

// Latest rates (most recent date in DB)
ExchangeRate::latest()->get();

// Date range
ExchangeRate::betweenDates('2026-04-01', '2026-04-23')
    ->forCurrency('GBP')
    ->orderBy('rate_date')
    ->get();
```

---

REST API (Optional)
-------------------

[](#rest-api-optional)

If you want to expose rates over HTTP, register these routes in your `routes/api.php`:

```
use Pk305\CbkForex\Http\Controllers\ExchangeRateController;

Route::prefix('cbk-forex')->group(function () {
    Route::get('/rates',              [ExchangeRateController::class, 'latest']);
    Route::get('/rates/{date}',       [ExchangeRateController::class, 'forDate']);
    Route::get('/rates/currency/{code}', [ExchangeRateController::class, 'history']);
});
```

### Example Responses

[](#example-responses)

**`GET /api/cbk-forex/rates`**

```
{
  "data": [
    {
      "id": 1,
      "rate_date": "2026-04-23",
      "currency_label": "US DOLLAR",
      "currency_code": "USD",
      "currency_name": "US Dollar",
      "rate": 129.21
    }
  ],
  "meta": { "date": "2026-04-23", "count": 21 }
}
```

**`GET /api/cbk-forex/rates/currency/USD?days=7`**

```
{
  "data": [ ... ],
  "meta": { "currency_code": "USD", "days": 7, "count": 7 }
}
```

---

Supported Currencies
--------------------

[](#supported-currencies)

CBK LabelISO CodeNameUS DOLLARUSDUS DollarSTG POUNDGBPSterling PoundEUROEUREuroS FRANCCHFSwiss FrancAUSTRALIAN $AUDAustralian DollarCAN $CADCanadian DollarHONGKONG DOLLARHKDHong Kong DollarSINGAPORE DOLLARSGDSingapore DollarCHINESE YUANCNYChinese YuanJPY (100)JPYJapanese Yen (per 100)IND RUPEEINRIndian RupeeDAN KRONERDKKDanish KroneNOR KRONERNOKNorwegian KroneSW KRONERSEKSwedish KronaSA RANDZARSouth African RandSAUDI RIYALSARSaudi RiyalAE DIRHAMAEDUAE DirhamKES / RWFRWFRwandan FrancKES / BIFBIFBurundian FrancKES / TSHSTZSTanzanian ShillingKES / USHSUGXUgandan Shilling---

Testing
-------

[](#testing)

```
composer test
```

---

License
-------

[](#license)

MIT

###  Health Score

40

—

FairBetter than 86% of packages

Maintenance90

Actively maintained with recent releases

Popularity11

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity43

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~0 days

Total

2

Last Release

47d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/85618640?v=4)[Kennedy Mwanzi](/maintainers/pk305)[@pk305](https://github.com/pk305)

---

Top Contributors

[![pk305](https://avatars.githubusercontent.com/u/85618640?v=4)](https://github.com/pk305 "pk305 (2 commits)")

---

Tags

laravelcurrencyexchange ratesforexkenyacbk

###  Code Quality

TestsPHPUnit

### Embed Badge

![Health badge](/badges/pk305-cbk-forex/health.svg)

```
[![Health](https://phpackages.com/badges/pk305-cbk-forex/health.svg)](https://phpackages.com/packages/pk305-cbk-forex)
```

###  Alternatives

[psalm/plugin-laravel

Psalm plugin for Laravel

3325.1M337](/packages/psalm-plugin-laravel)[larastan/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

6.4k51.0M7.4k](/packages/larastan-larastan)[spatie/laravel-health

Monitor the health of a Laravel application

88011.3M149](/packages/spatie-laravel-health)[spatie/laravel-export

Create a static site bundle from a Laravel app

670139.5k6](/packages/spatie-laravel-export)[simplestats-io/laravel-client

Analytics for Laravel. Track visitors, registrations, and payments. Discover which channels actually drive revenue, not just traffic. Server-side, GDPR compliant, ad-blocker proof.

5019.3k](/packages/simplestats-io-laravel-client)[calebdw/larastan

Larastan - Discover bugs in your code without running it. A phpstan/phpstan extension for Laravel

15104.9k4](/packages/calebdw-larastan)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
