PHP code example of easybdit / laravel-mikrotik

1. Go to this page and download the library: Download easybdit/laravel-mikrotik library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

easybdit / laravel-mikrotik example snippets


'connections' => [
    'default' => [ /* ... */ ],

    'branch-01' => [
        'transport'  => 'rest',
        'host'       => env('MIKROTIK_BRANCH01_HOST'),
        'username'   => env('MIKROTIK_BRANCH01_USERNAME'),
        'password'   => env('MIKROTIK_BRANCH01_PASSWORD'),
        'verify_tls' => true,
        'timeout'    => 10,
    ],
],

use Easybdit\LaravelMikrotik\Facades\Mikrotik;

$router = Mikrotik::connection();            // the default connection
$router = Mikrotik::connection('branch-01'); // a specific named connection

$resource = $router->resource();
echo $resource->version;      // e.g. "7.15 (stable)"
echo $resource->boardName;    // e.g. "RB3011UiAS"
echo $resource->cpuLoad;      // int, percent
echo $resource->freeMemory;   // int, bytes

$health = $router->health();
if ($health->has('cpu-temperature')) {
    echo $health->get('cpu-temperature')->value; // e.g. 43 (int)
    echo $health->get('cpu-temperature')->type;  // e.g. "C"
}
// Devices expose different sensors — iterate whatever is actually there:
foreach ($health as $sensor) {
    echo "{$sensor->name}: {$sensor->value}{$sensor->type}\n";
}

$interfaces = $router->interfaces();
$eth1 = $interfaces->get('ether1');
echo $eth1->type;      // "ether"
echo $eth1->running;   // bool
echo $eth1->rxByte;    // int, cumulative bytes received since last reset/reboot

foreach ($router->interfaces() as $interface) {
    echo "{$interface->name}: {$interface->rxByte} rx / {$interface->txByte} tx\n";
}

$before = $router->interfaces()->get('ether1')->rxByte;
sleep(5);
$after = $router->interfaces()->get('ether1')->rxByte;
$bytesPerSecond = ($after - $before) / 5;

$rate = $router->interfaceRate('ether1');
echo $rate->rxBitsPerSecond;    // int
echo $rate->txBitsPerSecond;    // int
echo $rate->rxPacketsPerSecond; // int

foreach ($router->logs() as $entry) {
    echo "{$entry->time} [{$entry->topics}] {$entry->message}\n";
}

// Simple equality filtering (sent as a REST query-string parameter):
$criticalOnly = $router->logs(['topics' => 'critical']);

$addresses = $router->menu('ip/address')->get();

foreach ($addresses as $address) {
    echo "{$address['address']} on {$address['interface']}\n";
}

// Simple equality filtering — the same `?field=value` form logs() uses:
$onBridge1 = $router->menu('ip/address')->get(['interface' => 'bridge1']);

// A single item by its RouterOS ".id" (e.g. "*1") or, where the menu
// supports it, its name (e.g. "ether1"):
$item = $router->menu('interface')->find('ether1');

// OR: everything that's type=ether OR type=bridge --
// confirmed against a real device: 11 ether + 1 bridge = 12 rows.
$router->menu('interface')->query(['type=ether', 'type=bridge', '#|']);

// Limit which fields come back (smaller/faster response):
$router->menu('ip/address')->query(['dynamic=true'], proplist: ['.id', 'address']);

// proplist alone, no filter:
$router->menu('interface')->query(proplist: ['name', 'type']);

use Easybdit\LaravelMikrotik\Exceptions\RouterOsException;

$addresses = $router->ip()->addresses();

$addresses->list();                              // Collection<DTO\IpAddress>
$addresses->list(['interface' => 'bridge1']);     // simple equality filter
$addresses->find('*1');                           // DTO\IpAddress, by ".id" or name

$created = $addresses->add([
    'address'   => '192.168.88.1/24', // led": "false"}
$addresses->remove($created->id);                 // DELETE — RouterOS's documented empty-body success

$iface = $router->interface();

$iface->list();                              // Collection<DTO\InterfaceRecord>
$iface->list(['type' => 'ether']);           // simple equality filter
$iface->find('ether7');                      // DTO\InterfaceRecord, by name or ".id"

$iface->update('ether7', ['comment' => 'uplink']);
$iface->disable('ether7');                   // PATCH {"disabled": "true"}
$iface->enable('ether7');                    // PATCH {"disabled": "false"}

$filter = $router->firewall()->filter();

$filter->list();                              // Collection<DTO\FirewallFilterRule>
$filter->list(['chain' => 'forward']);        // simple equality filter

$rule = $filter->add([
    'chain'  => 'forward', // le->id);
$filter->remove($rule->id);

$servers = $router->dhcp()->servers(); // /ip/dhcp-server
$leases  = $router->dhcp()->leases();  // /ip/dhcp-server/lease

$servers->list();                        // Collection<DTO\DhcpServer>
$server = $servers->add(['name' => 'dhcp2', 'interface' => 'bridge2', 'disabled' => true]);
$servers->update($server->id, ['comment' => 'secondary']);
$servers->enable($server->id);
$servers->disable($server->id);
$servers->remove($server->id);

$leases->list();                         // Collection<DTO\DhcpLease>
$lease = $leases->add(['address' => '192.168.88.50', 'mac-address' => 'AA:BB:CC:DD:EE:FF']);
$leases->update($lease->id, ['comment' => 'reserved']);
$leases->remove($lease->id);

$secrets = $router->ppp()->secrets();

$secrets->list();                        // Collection<DTO\PppSecret> -- no passwords
$secret = $secrets->add([
    'name'     => 'a-new-username', // nt']);
$secrets->remove($secret->id);

$queue = $router->queue()->simple();

$queue->list();                          // Collection<DTO\SimpleQueue>
$q = $queue->add([
    'name'      => 'guest-limit', // > '5M/5M']);
$queue->disable($q->id);
$queue->remove($q->id);

$pools = $router->ip()->pools();

$pools->list();                          // Collection<DTO\IpPool>
$pool = $pools->add(['name' => 'dhcp-pool-2', 'ranges' => '192.168.89.10-192.168.89.100']);
$pools->update($pool->id, ['ranges' => '192.168.89.10-192.168.89.150']);
$pools->remove($pool->id);

$routes = $router->ip()->routes();

$routes->list();                          // Collection<DTO\IpRoute>
$route = $routes->add(['dst-address' => '10.10.10.0/24', 'gateway' => '192.168.88.1']);
$routes->update($route->id, ['comment' => 'branch link']);
$routes->remove($route->id);

$dns = $router->dns()->get();          // /ip/dns
echo $dns->servers;                    // e.g. "8.8.8.8,1.1.1.1"
$router->dns()->update(['servers' => '1.1.1.1,9.9.9.9']);

$identity = $router->systemIdentity()->get(); // /system/identity
echo $identity->name;                          // e.g. "MyRouter"
$router->systemIdentity()->update('NewRouterName');

$users = $router->users();            // /user
$users->list();                        // Collection<DTO\RouterUser>
$users->add(['name' => 'ops', 'password' => '...', 'group' => 'read']);
$users->disable('*5');

$sched = $router->scheduler();        // /system/scheduler
$sched->add(['name' => 'nightly', 'interval' => '1d', 'on-event' => '...', 'disabled' => true]);
$sched->enable('*3');

use Easybdit\LaravelMikrotik\Monitoring\SnapshotRecorder;

$snapshot = app(SnapshotRecorder::class)->record();          // default connection
$snapshot = app(SnapshotRecorder::class)->record('branch-01'); // a specific one

$snapshot->resource;    // array, same shape as RouterResource::toArray()
$snapshot->health;      // array keyed by sensor name
$snapshot->interfaces;  // array keyed by interface name

use Illuminate\Support\Facades\Schedule;

Schedule::command('mikrotik:monitor')->everyFiveMinutes()->withoutOverlapping();

use Easybdit\LaravelMikrotik\Models\MikrotikRule;

MikrotikRule::query()->create([
    'connection' => 'branch-01', // or null to apply to every connection
    'name'       => 'High CPU load',
    'metric'     => 'resource.cpu_load',
    'operator'   => '>',           // one of: > >= < <= == !=
    'threshold'  => 90,
    'enabled'    => true,          // default
]);

use Easybdit\LaravelMikrotik\Monitoring\RuleEvaluator;

$alerts = app(RuleEvaluator::class)->evaluate($snapshot); // list<MikrotikAlert>, newly-triggered only

use Easybdit\LaravelMikrotik\Monitoring\IncidentManager;

$transitions = app(IncidentManager::class)->reconcile($triggeredAlerts, $justResolvedAlerts);
$transitions['opened'];   // list<MikrotikIncident> newly opened this call
$transitions['resolved']; // list<MikrotikIncident> newly resolved this call

use Easybdit\LaravelMikrotik\Monitoring\AlertNotifier;

app(AlertNotifier::class)->notify($alert); // $alert: MikrotikAlert

use Easybdit\LaravelMikrotik\Monitoring\MonitoringAnalytics;

$analytics = app(MonitoringAnalytics::class);

$analytics->resourceTrend('branch-01', 'cpu_load', since: now()->subDay());
// list<array{captured_at: Carbon, value: mixed}>

$analytics->healthTrend('branch-01', 'cpu-temperature');
// same shape, over one health sensor's ->value

$analytics->interfaceCounterTrend('branch-01', 'ether1', 'rx_error');
// same shape, over one interface counter (rx_error/tx_error/rx_drop/tx_drop/etc.)

$analytics->interfaceRateHistory('branch-01', 'ether1', 'rx_byte');
// list<array{from: Carbon, to: Carbon, rate_per_second: float|null, counter_reset: bool}>
// computed between each pair of consecutive stored snapshots — NOT a live
// RouterOS reading (that's interfaceRate() from section 5).
// counter_reset=true (rate_per_second=null) instead of a misleading
// negative number when a reboot reset the counter between snapshots.

$analytics->alertHistory('branch-01');            // Collection<MikrotikAlert>, any status
$analytics->alertCountsByRuleMetric('branch-01'); // list<array{rule_id, metric, count}>

$analytics->openIncidents('branch-01');              // Collection<MikrotikIncident>, ongoing now
$analytics->incidentHistory('branch-01');            // Collection<MikrotikIncident>, any status
$analytics->incidentCountsByRule('branch-01');       // list<array{rule_id, count}>
$analytics->averageIncidentDurationSeconds('branch-01'); // float|null — resolved incidents only

$router = Mikrotik::connection();

$router->resource();               // should return version/board info
$router->health();                 // should return whatever sensors your device has
$router->interfaces();             // should list your device's interfaces
$router->ip()->addresses()->list(); // should list your device's configured addresses

$addresses = $router->ip()->addresses();

// 1. List existing addresses.
$before = $addresses->list();

// 2. Confirm no collision with your chosen test value.
foreach ($before as $a) {
    if ($a->address === '203.0.113.99/32') {
        throw new RuntimeException('Already exists — pick a different test value.');
    }
}

// 3. Add.
$created = $addresses->add(['address' => '203.0.113.99/32', 'interface' => 'your-idle-interface']);

// 4. Find/list to confirm it.
$found = $addresses->find($created->id);

// 5. Update a harmless field.
$addresses->update($created->id, ['comment' => 'temporary-test-delete-me']);

// 6. Verify the update.
$addresses->find($created->id)->comment; // should read back what you set

// 7. Disable.
$addresses->disable($created->id);

// 8. Verify it is actually disabled.
$addresses->find($created->id)->disabled; // should be true

// 9. Enable.
$addresses->enable($created->id);

// 10. Verify it is actually enabled.
$addresses->find($created->id)->disabled; // should be false

// 11. Remove.
$addresses->remove($created->id);

// 12. Verify it is gone.
$addresses->list()->contains(fn ($a) => $a->address === '203.0.113.99/32'); // should be false
bash
php artisan vendor:publish --tag=mikrotik-config
bash
php artisan vendor:publish --tag=mikrotik-migrations
php artisan migrate
bash
php artisan mikrotik:monitor                          # every configured connection
php artisan mikrotik:monitor --connection=branch-01    # a specific one (repeatable)