PHP code example of cjmellor / fal-ai-laravel

1. Go to this page and download the library: Download cjmellor/fal-ai-laravel 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/ */

    

cjmellor / fal-ai-laravel example snippets


use Cjmellor\FalAi\Facades\FalAi;

$response = FalAi::model('fal-ai/flux/schnell')
    ->prompt('A beautiful sunset over mountains')
    ->imageSize('landscape_4_3')
    ->run();

$requestId = $response->requestId;

// config/fal-ai.php
'drivers' => [
    'fal' => [
        'default_model' => 'fal-ai/flux/schnell',
    ],
],

// Usage
$response = FalAi::model()
    ->prompt('A cozy cabin in the woods')
    ->run();

$response = FalAi::model('fal-ai/flux/dev')
    ->prompt('A detailed portrait')
    ->queue() // Optional - queue is the default
    ->run();

// Returns immediately with request_id
$requestId = $response->requestId;

$response = FalAi::model('fal-ai/flux/schnell')
    ->prompt('A quick sketch')
    ->sync()
    ->run();

// Returns the complete result
$images = $response->json()['images'];

// Check status
$status = FalAi::driver('fal')->status($requestId, 'fal-ai/flux/dev');

if ($status->json()['status'] === 'COMPLETED') {
    // Get the result
    $result = FalAi::driver('fal')->result($requestId, 'fal-ai/flux/dev');
    $images = $result->json()['images'];
}

// Cancel a queued request
FalAi::driver('fal')->cancel($requestId, 'fal-ai/flux/dev');

$response = FalAi::model('fal-ai/flux/schnell')
    ->prompt('A fox in a forest')
    ->run();

$response->requestId;    // Request ID
$response->statusUrl;    // URL to check status
$response->responseUrl;  // URL to get result
$response->cancelUrl;    // URL to cancel

$stream = FalAi::model('fal-ai/flux/schnell')
    ->prompt('A dancing robot')
    ->stream();

// Process the stream response
$stream->getResponse();

$response = FalAi::model('fal-ai/flux/schnell')
    ->prompt('A beautiful landscape')
    ->withWebhook('https://yourapp.com/webhooks/fal')
    ->run();

$response = FalAi::model('fal-ai/flux/schnell')
    ->withWebhook(url('/webhooks/fal'))
    ->prompt('Your prompt')
    ->run();

use Cjmellor\FalAi\Middleware\VerifyFalWebhook;

Route::post('/webhooks/fal-custom', function (Request $request) {
    $payload = $request->json()->all();

    if ($payload['status'] === 'OK') {
        $images = $payload['data']['images'];
        // Process images
    }

    return response()->json(['status' => 'processed']);
})->middleware(VerifyFalWebhook::class);

use Cjmellor\FalAi\Services\WebhookVerifier;
use Cjmellor\FalAi\Exceptions\WebhookVerificationException;

$verifier = new WebhookVerifier();

try {
    $verifier->verify($request);
    // Webhook is valid
} catch (WebhookVerificationException $e) {
    // Verification failed
}

$pricing = FalAi::platform()
    ->pricing()
    ->forEndpoints(['fal-ai/flux/dev', 'fal-ai/flux/schnell'])
    ->get();

$unitPrice = $pricing->getUnitPriceFor('fal-ai/flux/dev');

// Estimate by API calls
$estimate = FalAi::platform()
    ->estimateCost()
    ->historicalApiPrice()
    ->endpoint('fal-ai/flux/dev', callQuantity: 100)
    ->estimate();

echo $estimate->totalCost; // e.g., 2.50

// Estimate by billing units
$estimate = FalAi::platform()
    ->estimateCost()
    ->unitPrice()
    ->endpoint('fal-ai/flux/dev', unitQuantity: 100)
    ->estimate();

$usage = FalAi::platform()
    ->usage()
    ->forEndpoint('fal-ai/flux/dev')
    ->between('2025-01-01T00:00:00Z', '2025-01-31T23:59:59Z')
    ->timeframe('day')
    ->withSummary()
    ->get();

$totalCost = $usage->getTotalCost();
$totalQuantity = $usage->getTotalQuantity();

$analytics = FalAi::platform()
    ->analytics()
    ->forEndpoint('fal-ai/flux/dev')
    ->between('2025-01-01', '2025-01-31')
    ->withAllMetrics()
    ->get();

$totalRequests = $analytics->getTotalRequests();
$successRate = $analytics->getSuccessRate();

$response = FalAi::platform()
    ->deleteRequestPayloads('req_123456789')
    ->delete();

if (!$response->hasErrors()) {
    echo "Deleted successfully";
}

FalAi::model('fal-ai/flux/schnell')
    ->prompt('A sunset')           // prompt
    ->imageSize('1024x1024')       // image_size
    ->numInferenceSteps(50)        // num_inference_steps
    ->guidanceScale(7.5)           // guidance_scale
    ->negativePrompt('blurry')     // negative_prompt
    ->numImages(2)                 // num_images
    ->seed(12345)                  // seed
    ->run();

$response = FalAi::model('fal-ai/flux/schnell')
    ->with([
        'prompt' => 'A landscape',
        'image_size' => '1024x1024',
        'num_images' => 2,
    ])
    ->run();

$base = FalAi::model('fal-ai/flux/schnell')
    ->imageSize('1024x1024')
    ->numImages(1);

$request1 = $base->promptImmutable('A dragon');
$request2 = $base->promptImmutable('A unicorn');

// $base is unchanged

$response = FalAi::model('fal-ai/flux/schnell')
    ->prompt('A sunset')
    ->when($highQuality, fn($req) => $req->numInferenceSteps(100))
    ->unless($skipSeed, fn($req) => $req->seed(42))
    ->run();

// config/fal-ai.php
return [
    'default' => env('AI_DRIVER', 'fal'),

    'drivers' => [
        'fal' => [
            'api_key' => env('FAL_API_KEY'),
            'base_url' => env('FAL_BASE_URL', 'https://queue.fal.run'),
            'sync_url' => env('FAL_SYNC_URL', 'https://fal.run'),
            'platform_base_url' => env('FAL_PLATFORM_URL', 'https://api.fal.ai'),
            'default_model' => env('FAL_DEFAULT_MODEL'),
            'webhook' => [
                'jwks_cache_ttl' => 86400,
                'timestamp_tolerance' => 300,
                'verification_timeout' => 10,
            ],
        ],
    ],
];

use Saloon\Exceptions\Request\RequestException;
use Cjmellor\FalAi\Exceptions\WebhookVerificationException;

try {
    $response = FalAi::model('fal-ai/flux/schnell')
        ->prompt('A sunset')
        ->run();
} catch (RequestException $e) {
    $status = $e->getResponse()->status();
    $body = $e->getResponse()->json();
} catch (WebhookVerificationException $e) {
    // Webhook verification failed
}

use Cjmellor\FalAi\Facades\FalAi as Ai;

$response = Ai::driver('replicate')
    ->model('stability-ai/sdxl')
    ->prompt('A majestic dragon')
    ->numOutputs(2)
    ->run();

// Format: owner/model
->model('stability-ai/sdxl')

// Format: owner/model:version
->model('your-username/my-custom-model:da77bc59ee60...')

$response = Ai::driver('replicate')
    ->model('stability-ai/sdxl')
    ->prompt('A landscape')
    ->run();

// Poll for completion
$status = Ai::driver('replicate')->status($response->id);

// Status helpers
$status->isRunning();    // starting or processing
$status->isSucceeded();  // completed successfully
$status->isFailed();     // failed
$status->isCanceled();   // canceled
$status->isTerminal();   // any final state

// Get result when complete
if ($status->isSucceeded()) {
    $output = $status->output;
}

$response = Ai::driver('replicate')
    ->model('stability-ai/sdxl')
    ->prompt('A sunset')
    ->withWebhook('https://yourapp.com/webhooks/replicate')
    ->run();

$deployment = Ai::driver('replicate')
    ->deployments()
    ->create('my-image-generator')
    ->model('stability-ai/sdxl')
    ->version('da77bc59ee60423279fd632efb4795ab731d9e3ca9705ef3341091fb989b7eaf')
    ->hardware('gpu-t4')
    ->instances(1, 5)  // min, max
    ->save();

echo $deployment->name;       // 'my-image-generator'
echo $deployment->hardware(); // 'gpu-t4'

$collection = Ai::driver('replicate')->deployments()->list();

foreach ($collection->results() as $deployment) {
    echo $deployment->name . ': ' . $deployment->hardware();
}

// Pagination
if ($collection->hasMore()) {
    $nextUrl = $collection->next();
}

// Get
$deployment = Ai::driver('replicate')->deployments()->get('owner', 'name');

// Update
$updated = Ai::driver('replicate')
    ->deployments()
    ->update('owner', 'name')
    ->hardware('gpu-a100-large')
    ->instances(2, 10)
    ->save();

// Delete
Ai::driver('replicate')->deployments()->delete('owner', 'name');

$prediction = Ai::driver('replicate')
    ->deployment('owner/my-deployment')
    ->with(['prompt' => 'A sunset over mountains'])
    ->webhook('https://example.com/webhook')
    ->run();

// Use prediction ID with standard status/result methods
$status = Ai::driver('replicate')->status($prediction->id);
bash
php artisan vendor:publish --tag=fal-ai-config