PHP code example of mindtwo / laravel-platform-manager

1. Go to this page and download the library: Download mindtwo/laravel-platform-manager 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/ */

    

mindtwo / laravel-platform-manager example snippets


// config/platform.php

return [
    // Eloquent model used as the platform. Swap this for your own model that extends Platform.
    'model' => \mindtwo\LaravelPlatformManager\Models\Platform::class,

    // HTTP headers used for M2M token auth.
    'header_names' => [
        'token' => 'X-Platform-Token',

        // Legacy header accepted during a grace period. Set to null to disable.
        'token_legacy' => 'X-Context-Platform-Public-Auth-Token',
    ],

    // Session key used by the session resolver.
    'session_key' => 'platform_id',
];

// routes/api.php
Route::middleware('resolve-platform:token')->group(function () {
    // platform() is available here
});

// Try token first, fall back to hostname
Route::middleware('resolve-platform:token|host')->group(function () { ... });

// Check whether a platform has been resolved
platform()->isResolved(); // bool

// Get the underlying Eloquent model
platform()->get(); // ?PlatformModel

// Read any model attribute directly
platform()->hostname;
platform()->uuid;

// Read platform settings (dot notation)
platform()->setting('mail.from');
platform()->setting('billing.plan', 'free');

// Which resolver matched
platform()->resolver(); // 'token' | 'host' | 'context' | 'session' | ...

$platform->update(['scopes' => ['read']]);

$platform->authTokens()->create([
    'scopes' => ['read', 'write'],
]);

// In a controller, middleware, policy, etc.
if (! platform()->can('write')) {
    abort(403);
}

$token->hasScope('admin');           // bool
$token->scopes;                      // array<string>
$token->isExpired();                 // bool

AuthToken::withScope('read')->get(); // query scope

$platform->authTokens()->create([
    'scopes'     => ['read'],
    'expired_at' => now()->addDays(30),
]);

// Store the current platform in the session (e.g. after an admin selects a platform)
platform()->saveToSession($platformModel);

// Or if it's already set:
platform()->set($model, 'admin');
platform()->saveToSession();

// Clear on logout / platform switch
platform()->clearFromSession();

platform()->use($otherPlatform, function () {
    // platform() resolves $otherPlatform here
    Mail::send(...);
});

// platform() is restored here

use mindtwo\LaravelPlatformManager\Jobs\Concerns\HasPlatformContext;

class ProcessOrder implements ShouldQueue
{
    use HasPlatformContext;

    public function __construct(private Order $order)
    {
        $this->capturePlatformContext(); // call at end of constructor
    }

    public function handle(): void
    {
        $this->restorePlatformContext(); // call at start of handle
        // platform() is now resolved
    }
}

// app/Models/Platform.php
use mindtwo\LaravelPlatformManager\Models\Platform as BasePlatform;

class Platform extends BasePlatform
{
    // add columns, relationships, scopes ...
}

// config/platform.php
'model' => \App\Models\Platform::class,

use mindtwo\LaravelPlatformManager\Traits\BelongsToPlatform;

class Article extends Model
{
    use BelongsToPlatform;
}

// Scopes
Article::forCurrentPlatform()->get();
Article::forPlatform($platform)->get();
Article::forPlatform(42)->get();

Route::middleware(['resolve-platform:token', 'platform-scope:write'])->group(function () {
    // platform must have the 'write' scope
});

// Multiple scopes — all must be present
Route::middleware(['resolve-platform:token', 'platform-scope:read,write'])->group(function () {
    // ...
});

use mindtwo\LaravelPlatformManager\Traits\BelongsToManyPlatforms;

class Article extends Model
{
    use BelongsToManyPlatforms;
}

// Scopes
Article::forCurrentPlatform()->get();
Article::forPlatform($platform)->get();
Article::forPlatform(42)->get();

// Relationship
$article->platforms; // Collection of Platform models

public function getPlatformPivotTable(): string
{
    return 'article_platform';
}

// app/Settings/PlatformSettings.php
use mindtwo\LaravelPlatformManager\Settings\PlatformSettings as BaseSettings;

class PlatformSettings extends BaseSettings
{
    protected array $encrypted = ['apiSecret', 'smtpPassword'];

    public ?string $appName = null;
    public ?string $apiSecret = null;   // encrypted at rest
    public ?string $smtpPassword = null; // encrypted at rest
    public ?string $billingPlan = null;
}

// config/platform.php
'settings' => \App\Settings\PlatformSettings::class,

// Via the helper (dot notation, works for any depth)
platform()->setting('appName');
platform()->setting('mail.host', 'localhost'); // nested via overflow

// Via the model directly
$platform->settings->appName;
$platform->setting('appName');

// Assign properties directly
$platform->settings->appName = 'My App';
$platform->settings->apiSecret = 's3cr3t'; // stored encrypted
$platform->save();

// Or replace the whole DTO
$platform->update(['settings' => ['appName' => 'My App', 'apiSecret' => 's3cr3t']]);

$platform->update([
    'settings' => [
        'config' => [
            'mail.default' => 'ses',
            'app.name'     => 'My Platform',
        ],
    ],
]);

use mindtwo\LaravelPlatformManager\Repositories\PlatformRepository;

class PlatformController extends Controller
{
    public function __construct(protected PlatformRepository $platforms) {}
}

$repository->resolveByToken($request);    // ?array{PlatformModel, array<string>}
$repository->resolveByHostname($request); // ?PlatformModel
$repository->resolveByContext($request);  // ?PlatformModel
$repository->resolveBySession($request);  // ?PlatformModel

$repository->findByHostname('example.com'); // ?PlatformModel
$repository->findByContext('my-context');   // ?PlatformModel
$repository->findByUuid('uuid-string');     // ?PlatformModel
$repository->findActiveById(1);            // ?PlatformModel

// Returns [PlatformModel, effectiveScopes]|null
$repository->findByTokenWithScopes($rawToken);

$repository->allActive();                     // Collection<PlatformModel>
$repository->index(['is_active' => true]);    // Collection<PlatformModel>
$repository->index(['hostname' => 'app.io']); // Collection<PlatformModel>
$repository->count(['is_active' => true]);    // int
$repository->search('app', ['is_active' => true]); // LengthAwarePaginator

use mindtwo\LaravelPlatformManager\Testing\PlatformFake;

PlatformFake::make(['hostname' => 'test.com']);

// With resolver and scopes
PlatformFake::make(['hostname' => 'test.com'], resolver: 'token', scopes: ['read', 'write']);

// Reset back to unresolved
PlatformFake::reset();

use mindtwo\LaravelPlatformManager\Testing\InteractsWithPlatform;

class MyTest extends TestCase
{
    use InteractsWithPlatform;

    protected function tearDown(): void
    {
        $this->clearPlatform();
        parent::tearDown();
    }

    public function test_something(): void
    {
        $this->setPlatform(['hostname' => 'test.com'], scopes: ['read']);

        $this->assertPlatformResolved();
        $this->assertPlatformCan('read');
        $this->assertPlatformCannot('write');
        $this->assertPlatformResolver('fake');
    }
}

// Before (config/app.php or auto-discovery override)
mindtwo\LaravelPlatformManager\Providers\LaravelPlatformManagerProvider::class

// After
mindtwo\LaravelPlatformManager\LaravelPlatformManagerProvider::class

// Before (config/platform-resolver.php)
'model'       => Platform::class,
'headerNames' => [
    AuthTokenTypeEnum::Public()  => 'X-Context-Platform-Public-Auth-Token',
    AuthTokenTypeEnum::Secret()  => 'X-Context-Platform-Secret-Auth-Token',
],
'webhooks'    => [ ... ],

// After (config/platform.php)
'model'        => Platform::class,
'header_names' => [
    'token' => 'X-Platform-Token',
],
'session_key'  => 'platform_id',

Schema::table('platforms', function (Blueprint $table) {
    // Remove v2-only columns (skip any you wish to keep in your own schema)
    $table->dropColumn([
        'owner_id',
        'is_main',
        'is_headless',
        'name',
        'default_locale',
        'available_locales',
    ]);

    // Widen hostname to 100 chars
    $table->string('hostname', 100)->nullable()->change();

    // Add new columns
    $table->string('context')->nullable()->unique()->after('additional_hostnames');
    $table->json('scopes')->nullable()->after('context');
    $table->json('settings')->nullable()->after('scopes');
});

Schema::table('auth_tokens', function (Blueprint $table) {
    // Drop v2 columns
    $table->dropForeign(['user_id']);
    $table->dropUnique(['platform_id', 'token']); // composite unique
    $table->dropColumn(['user_id', 'description']);
    $table->dropSoftDeletes();
    $table->dropColumn('type');

    // Add v4 columns
    $table->json('scopes')->default('[]')->after('platform_id');
    $table->datetime('expired_at')->nullable()->after('token');
});

// Run before dropping 'type'
DB::table('auth_tokens')->where('type', 1)->update(['scopes' => '["read","write"]']); // Secret → full access
DB::table('auth_tokens')->where('type', 2)->update(['scopes' => '["read"]']);          // Public → read only

// Before
app(PlatformResolver::class)->getCurrentPlatform()
resolve(PlatformResolver::class)->getCurrentPlatform()

// After
platform()->get()

// Before — auth check
app(PlatformResolver::class)->checkAuth(AuthTokenTypeEnum::Secret())

// After — scope check
platform()->can('write')

// Before
\mindtwo\LaravelPlatformManager\Middleware\PlatformSession::class

// After
'resolve-platform:session'

// Before — token-based routes
\mindtwo\LaravelPlatformManager\Middleware\ResolveBySecretToken::class
\mindtwo\LaravelPlatformManager\Middleware\ResolveByPublicToken::class

// After
'resolve-platform:token'

Route::middleware('resolve-platform:token|host|session')->group(...);

// Before
$table->smallInteger('type');

// After
$table->json('scopes')->default('[]');

Schema::table('auth_tokens', function (Blueprint $table) {
    $table->json('scopes')->default('[]')->after('platform_id');
    $table->dropColumn('type');
});

// Before
$token->type = AuthTokenTypeEnum::Secret;
$token->type = AuthTokenTypeEnum::Public;

// After — just assign scopes
$token->scopes = ['read', 'write'];

// Before
'header_names' => [
    'public' => 'X-Context-Platform-Public-Auth-Token',
    'secret' => 'X-Context-Platform-Secret-Auth-Token',
],

// After
'header_names' => [
    'token' => 'X-Platform-Token',
],

// Before
Route::middleware('resolve-platform:public-token|secret-token|host')->group(...);

// After
Route::middleware('resolve-platform:token|host')->group(...);

// Before
Platform::query()->byPublicAuthToken($token)->first();
Platform::query()->bySecretAuthToken($token)->first();

// After — single scope, expiry checked automatically
Platform::query()->byToken($token)->first();

if (platform()->can('write')) {
    // scope is in platform baseline or widened by the resolved token
}
bash
php artisan vendor:publish --provider="mindtwo\LaravelPlatformManager\LaravelPlatformManagerProvider" --tag=config
bash
php artisan vendor:publish --provider="mindtwo\LaravelPlatformManager\LaravelPlatformManagerProvider" --tag=migrations
php artisan migrate