PHP code example of litepie / masters

1. Go to this page and download the library: Download litepie/masters 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/ */

    

litepie / masters example snippets


// Single database with tenant_id column (default)
'tenancy_strategy' => 'single_db',

// Multiple databases per tenant
'tenancy_strategy' => 'multi_db',

// Schema-based separation
'tenancy_strategy' => 'schema',

'cache' => [
    'enabled' => true,
    'ttl' => 3600, // 1 hour
    'prefix' => 'masters',
],

'api' => [
    'enabled' => true,
    'prefix' => 'api/masters',
    'middleware' => ['api', 'throttle:60,1'],
    'rate_limit' => '60,1',
],

use Litepie\Masters\Facades\Masters;

// Set tenant context
Masters::setTenant('tenant_123');

// Get all countries
$countries = Masters::get('countries');

// Create new master data
$country = Masters::create('countries', [
    'name' => 'United States',
    'code' => 'US',
    'iso_code' => 'USA',
    'is_active' => true
]);

// Update master data
Masters::update('countries', $country->id, [
    'name' => 'United States of America'
]);

// Search master data
$results = Masters::search('countries', 'United');

use Litepie\Masters\Models\MasterData;
use Litepie\Masters\Models\MasterType;

// Get countries with states
$countries = MasterData::ofType('countries')
    ->with('children')
    ->active()
    ->get();

// Create hierarchical data
$usa = MasterData::ofType('countries')->where('code', 'US')->first();
$california = MasterData::create([
    'master_type_id' => MasterType::where('slug', 'states')->first()->id,
    'name' => 'California',
    'code' => 'CA',
    'parent_id' => $usa->id,
    'is_active' => true
]);

use Litepie\Masters\Facades\Masters;

// Set current tenant
Masters::setTenant('tenant_123');

// Get current tenant
$currentTenant = Masters::getCurrentTenant();

// Execute in tenant context
Masters::runForTenant('tenant_456', function() {
    $data = Masters::get('categories');
    // This will only get categories for tenant_456
});

// Clear tenant context
Masters::setTenant(null);

// Global data (available to all tenants)
$countries = MasterData::ofType('countries')->global()->get();

// Tenant-specific data
$categories = MasterData::ofType('categories')->tenant('tenant_123')->get();

// Both global and tenant data
$currencies = MasterData::ofType('currencies')->tenantOrGlobal()->get();

use Litepie\Masters\Models\MasterType;

$departmentType = MasterType::create([
    'name' => 'Departments',
    'slug' => 'departments',
    'description' => 'Organizational departments',
    'is_hierarchical' => true,
    'is_global' => false, // Tenant-specific
    'validation_rules' => [
        'name' => 'partments', [
    'name' => 'Human Resources',
    'code' => 'HR',
    'additional_data' => [
        'manager_email' => '[email protected]',
        'budget' => 50000,
        'location' => 'Building A, Floor 2'
    ]
]);

// Get full tree structure
$categoryTree = Masters::getHierarchical('categories');

// Get children of specific parent
$subCategories = Masters::getHierarchical('categories', $parentId);

// Get path of an item
$category = MasterData::find(123);
echo $category->getPath(); // "Electronics > Computers > Laptops"
echo $category->getPath(' / '); // "Electronics / Computers / Laptops"

// Check relationships
if ($category->hasChildren()) {
    $subcategories = $category->children;
}

if (!$category->isRoot()) {
    $parent = $category->parent;
}

// Get all ancestors
$ancestors = $category->ancestors();

// Get all descendants
$descendants = $category->descendants;

// Complex filtering
$data = Masters::get('countries', [
    'search' => 'United',
    'is_active' => true,
    'parent_id' => null
]);

// Using Eloquent scopes
$activeCountries = MasterData::ofType('countries')
    ->active()
    ->rootLevel()
    ->orderBy('name')
    ->get();

// Search with relationships
$countriesWithStates = MasterData::ofType('countries')
    ->whereHas('children', function($query) {
        $query->where('is_active', true);
    })
    ->with(['children' => function($query) {
        $query->active()->orderBy('name');
    }])
    ->get();

// Import from array
$countries = [
    ['name' => 'India', 'code' => 'IN', 'iso_code' => 'IND'],
    ['name' => 'China', 'code' => 'CN', 'iso_code' => 'CHN'],
    ['name' => 'Japan', 'code' => 'JP', 'iso_code' => 'JPN'],
];

$results = Masters::import('countries', $countries);
// Returns: ['success' => 3, 'failed' => 0, 'errors' => []]

// Export to array
$exportData = Masters::export('countries', [
    'is_active' => true
]);

// Export specific fields
$exportData = MasterData::ofType('countries')
    ->select(['name', 'code', 'iso_code'])
    ->active()
    ->get()
    ->toArray();

// In config/masters.php
'api' => [
    'middleware' => ['api', 'auth:sanctum', 'throttle:60,1'],
],

// In config/masters.php
'admin' => [
    'enabled' => true,
    'prefix' => 'admin/masters',
    'middleware' => ['web', 'auth', 'can:manage-masters'],
],

// In MasterType creation
$type = MasterType::create([
    'name' => 'Products',
    'slug' => 'products',
    'validation_rules' => [
        'name' => '_data,id'
    ]
]);

use Litepie\Masters\Models\MasterData;

// Listen for master data events
MasterData::creating(function ($masterData) {
    // Auto-generate slug
    if (empty($masterData->slug)) {
        $masterData->slug = Str::slug($masterData->name);
    }
});

MasterData::created(function ($masterData) {
    // Clear cache, send notifications, etc.
    Log::info("Master data created: {$masterData->name}");
});

// Custom cache key generation
class CustomMasterData extends MasterData
{
    public function getCacheKey(): string
    {
        return "custom:master:{$this->masterType->slug}:{$this->id}:{$this->tenant_id}";
    }
}

// Add custom indexes in migration
Schema::table('master_data', function (Blueprint $table) {
    $table->index(['tenant_id', 'master_type_id', 'is_active']);
    $table->index(['parent_id', 'sort_order']);
    $table->fullText(['name', 'description']); // For advanced search
});

use Litepie\Masters\Facades\Masters;
use Litepie\Masters\Models\MasterType;

class MasterDataTest extends TestCase
{
    public function test_can_create_master_data()
    {
        // Create master type
        $type = MasterType::create([
            'name' => 'Test Categories',
            'slug' => 'test-categories',
            'is_global' => false
        ]);

        // Set tenant
        Masters::setTenant('test_tenant');

        // Create master data
        $category = Masters::create('test-categories', [
            'name' => 'Test Category',
            'code' => 'TEST'
        ]);

        $this->assertNotNull($category);
        $this->assertEquals('Test Category', $category->name);
        $this->assertEquals('test_tenant', $category->tenant_id);
    }

    public function test_hierarchical_relationships()
    {
        $parent = Masters::create('categories', [
            'name' => 'Parent Category',
            'code' => 'PARENT'
        ]);

        $child = Masters::create('categories', [
            'name' => 'Child Category',
            'code' => 'CHILD',
            'parent_id' => $parent->id
        ]);

        $this->assertTrue($parent->hasChildren());
        $this->assertFalse($child->isRoot());
        $this->assertEquals($parent->id, $child->parent->id);
    }
}

public function test_api_endpoints()
{
    $response = $this->getJson('/api/masters/countries');
    $response->assertStatus(200)
             ->assertJsonStructure(['data', 'count']);

    $response = $this->postJson('/api/masters/countries', [
        'name' => 'Test Country',
        'code' => 'TC',
        'is_active' => true
    ]);
    $response->assertStatus(201);
}
bash
# Publish everything
php artisan vendor:publish --provider="Litepie\Masters\MastersServiceProvider"

# Or publish selectively
php artisan vendor:publish --provider="Litepie\Masters\MastersServiceProvider" --tag="config"
php artisan vendor:publish --provider="Litepie\Masters\MastersServiceProvider" --tag="migrations"
php artisan vendor:publish --provider="Litepie\Masters\MastersServiceProvider" --tag="views"
php artisan vendor:publish --provider="Litepie\Masters\MastersServiceProvider" --tag="assets"
bash
php artisan migrate
bash
# Install package and create default master types
php artisan masters:install

# Seed sample data (optional)
php artisan masters:seed
bash
# Install package and create default types
php artisan masters:install

# Force reinstall
php artisan masters:install --force

# Seed all sample data
php artisan masters:seed

# Seed specific type
php artisan masters:seed countries