PHP code example of ktr / business-central-sdk

1. Go to this page and download the library: Download ktr/business-central-sdk 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/ */

    

ktr / business-central-sdk example snippets


use Ktr\BusinessCentral\Models\ApiV20\SalesOrders;
use Ktr\BusinessCentral\Models\ApiV20\SalesOrderLines;
use Ktr\BusinessCentral\Models\ApiV20\Customers;
use Ktr\BusinessCentral\Models\ApiV20\Items;

// Create a sales order
$order = SalesOrders::create([
    'customerId' => '{customer-id}',
    'shipToName' => 'John Doe',
    'shipToAddress' => '123 Main St',
    'salesOrderLines' => [
        [
            'lineType' => 'Item',
            'itemId' => '{item-id}',
            'quantity' => 5,
            'unitPrice' => 29.99
        ]
    ]
]);

// Query with filters
$orders = SalesOrders::query()
    ->where('customerId', '{customer-id}')
    ->where('totalAmount', '>', 1000)
    ->orderBy('orderDate', 'desc')
    ->take(10)
    ->get();

// Select specific fields
$customer = Customers::select('id', 'displayName', 'email', 'phoneNumber')
    ->where('number', 'C-001')
    ->first();

// Expand related data
$order = SalesOrders::select('number', 'customerId', 'totalAmount')
    ->where('number', 'SO-001')
    ->expand(SalesOrderLines::class) // Load order lines
    ->first();

// Access expanded data
echo $order->number; // SO-001
echo $order->salesOrderLines[0]->quantity; // 5

// Update a record
$customer->email = '[email protected]';
$customer->phoneNumber = '+1-555-0123';
$customer->save();

// Delete a record
$order->delete();

use Illuminate\Support\Facades\Http;

// Create a sales order
$order = Http::businessCentral()->post('salesOrders', [
    'customerId' => '{customer-id}',
    'shipToName' => 'Jane Smith',
    'salesOrderLines' => [
        [
            'lineType' => 'Item',
            'itemId' => '{item-id}',
            'quantity' => 3,
            'unitPrice' => 49.99
        ]
    ]
]);

// Get customers with query parameters
$customers = Http::businessCentral()->get('customers', [
    '$filter' => "city eq 'New York'",
    '$select' => 'id,displayName,email',
    '$top' => 20
]);

// Update with PATCH
$response = Http::businessCentral()->patch("customers('{id}')", [
    'phoneNumber' => '+1-555-9999'
]);

use Ktr\BusinessCentral\Facades\BusinessCentral;

// Create a customer
$customer = BusinessCentral::post('customers', [
    'displayName' => 'Acme Corporation',
    'email' => '[email protected]',
    'phoneNumber' => '+1-555-1234',
    'addressLine1' => '456 Business Ave',
    'city' => 'San Francisco',
    'state' => 'CA',
    'postalCode' => '94102'
]);

// Get all items
$items = BusinessCentral::get('items');

// Get with filters
$items = BusinessCentral::get('items', [
    '$filter' => "type eq 'Inventory' and unitPrice gt 100",
    '$orderby' => 'displayName asc'
]);

use Ktr\BusinessCentral\Models\ApiV20\Items;

// Simple where clause
$items = Items::where('type', 'Inventory')->get();

// Multiple conditions
$items = Items::query()
    ->where('type', 'Inventory')
    ->where('unitPrice', '>', 50)
    ->where('blocked', false)
    ->get();

// Or conditions
$items = Items::query()
    ->where('type', 'Inventory')
    ->orWhere('type', 'Service')
    ->get();

// Contains search
$customers = Customers::whereContains('displayName', 'Tech')->get();

// Starts with
$customers = Customers::whereStartsWith('displayName', 'Acme')->get();

// Ends with
$items = Items::whereEndsWith('number', '-X')->get();

// In clause
$customers = Customers::whereIn('city', ['New York', 'Los Angeles', 'Chicago'])->get();

// Date filtering
$orders = SalesOrders::whereDateTime('orderDate', '>=', now()->subDays(30))->get();

// Complex grouped conditions
$items = Items::query()
    ->where(function($query) {
        $query->where('type', 'Inventory')
              ->where('unitPrice', '>', 100);
    })
    ->orWhere(function($query) {
        $query->where('type', 'Service')
              ->where('unitCost', '<', 50);
    })
    ->get();

// Select specific fields only
$customers = Customers::select('id', 'displayName', 'email')
    ->get();

// Select with filtering
$items = Items::select('id', 'number', 'displayName', 'unitPrice')
    ->where('type', 'Inventory')
    ->orderBy('displayName')
    ->get();

use Ktr\BusinessCentral\Models\ApiV20\SalesInvoices;
use Ktr\BusinessCentral\Models\ApiV20\SalesInvoiceLines;

// Expand related entities
$invoice = SalesInvoices::query()
    ->expand(SalesInvoiceLines::class)
    ->first();

// Multiple expands
$order = SalesOrders::query()
    ->expand(SalesOrderLines::class, 'customer', 'shipmentMethod')
    ->where('number', 'SO-001')
    ->first();

// Order by single field
$customers = Customers::orderBy('displayName', 'asc')->get();

// Order by multiple fields
$items = Items::query()
    ->orderBy('type', 'asc')
    ->orderBy('unitPrice', 'desc')
    ->get();

// Simple pagination
$items = Items::take(10)->get(); // First 10 items

// Skip and take
$items = Items::skip(20)->take(10)->get(); // Items 21-30

// Lazy loading for large datasets (memory efficient)
Items::lazy(1000)->each(function ($item) {
    // Process each item without loading all into memory
    echo $item->displayName;
});

// Get all records (uses lazy loading internally)
$allItems = Items::all();

// Find by ID
$customer = Customers::find('{customer-id}');

// First matching record
$customer = Customers::where('email', '[email protected]')->first();

// Get all matching records
$customers = Customers::where('city', 'Boston')->get();

// Count records
$count = Customers::where('blocked', false)->count();

// String values - automatically quoted
Items::where('type', 'Inventory')->get();
// Generates: type eq 'Inventory'

// Numeric values - not quoted
Items::where('unitPrice', '>', 100)->get();
Items::where('quantity', 0)->get();
// Generates: unitPrice gt 100 and quantity eq 0

// Boolean values - not quoted
Items::where('blocked', false)->get();
Customers::where('taxLiable', true)->get();
// Generates: blocked eq false and taxLiable eq true

// DateTime/Carbon objects - auto-formatted to ISO 8601
Items::where('lastModifiedDateTime', '>=', Carbon::parse('2024-01-01'))->get();
// Generates: lastModifiedDateTime ge 2024-01-01T00:00:00.000Z

// Negative numbers work correctly
Customers::where('balanceDue', '<', 0)->get();
// Generates: balanceDue lt 0

// Real-world example: Items with inventory greater than zero
use Ktr\BusinessCentral\Models\ODataV4\ItemQuantities;

$items = ItemQuantities::query()
    ->where('Inventory', '>', 0)
    ->get();
// Generates: Inventory gt 0

use Ktr\BusinessCentral\Models\ApiV20\SalesOrders;
use Ktr\BusinessCentral\Models\ApiV20\Customers;
use Ktr\BusinessCentral\Models\ApiV20\Items;

// Find customer
$customer = Customers::where('number', 'C-001')->first();

// Find items
$item1 = Items::where('number', 'ITEM-001')->first();
$item2 = Items::where('number', 'ITEM-002')->first();

// Create order with multiple lines
$order = SalesOrders::create([
    'customerId' => $customer->id,
    'customerNumber' => $customer->number,
    'shipToName' => $customer->displayName,
    'shipToAddress' => $customer->addressLine1,
    'shipToCity' => $customer->city,
    'salesOrderLines' => [
        [
            'lineType' => 'Item',
            'itemId' => $item1->id,
            'quantity' => 10,
            'unitPrice' => $item1->unitPrice,
            'description' => $item1->displayName
        ],
        [
            'lineType' => 'Item',
            'itemId' => $item2->id,
            'quantity' => 5,
            'unitPrice' => $item2->unitPrice,
            'description' => $item2->displayName
        ]
    ]
]);

echo "Order created: {$order->number}";

use Ktr\BusinessCentral\Models\ApiV20\SalesInvoices;
use Carbon\Carbon;

// Get sales for last 30 days
$startDate = Carbon::now()->subDays(30);
$invoices = SalesInvoices::query()
    ->whereDateTime('orderDate', '>=', $startDate)
    ->select('id', 'number', 'customerId', 'totalAmountIncludingTax', 'orderDate')
    ->orderBy('orderDate', 'desc')
    ->get();

$totalRevenue = $invoices->sum('totalAmountIncludingTax');
$invoiceCount = $invoices->count();

echo "Total invoices: {$invoiceCount}\n";
echo "Total revenue: $" . number_format($totalRevenue, 2);

use Ktr\BusinessCentral\Models\ApiV20\Items;

// Get low stock items
$lowStockItems = Items::query()
    ->where('type', 'Inventory')
    ->where('inventory', '<', 10)
    ->select('id', 'number', 'displayName', 'inventory')
    ->orderBy('inventory', 'asc')
    ->get();

foreach ($lowStockItems as $item) {
    echo "{$item->displayName}: {$item->inventory} units in stock\n";

    // Your reorder logic here
    if ($item->inventory < 5) {
        // Send notification or create purchase order
    }
}

use Ktr\BusinessCentral\Models\ApiV20\Customers;

// Create new customer
$customer = Customers::create([
    'displayName' => 'New Customer Inc.',
    'email' => '[email protected]',
    'phoneNumber' => '+1-555-0100',
    'addressLine1' => '789 Customer Blvd',
    'city' => 'Seattle',
    'state' => 'WA',
    'postalCode' => '98101',
    'countryCode' => 'US',
    'currencyCode' => 'USD',
    'blocked' => false,
    'taxLiable' => true
]);

// Update customer information
$customer->email = '[email protected]';
$customer->creditLimit = 50000.00;
$customer->save();

// Find customers by city
$seattleCustomers = Customers::query()
    ->where('city', 'Seattle')
    ->where('blocked', false)
    ->select('displayName', 'email', 'phoneNumber')
    ->get();