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 FalAi\FalAi;

$falAi = new FalAi();

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

$response = $falAi->model('fal-ai/flux/dev')
    ->prompt('A futuristic cityscape')
    ->queue() // Explicit queue mode (optional, it's the default)
    ->run();

// Returns: ['request_id' => 'req_123...', 'status' => 'IN_QUEUE']

$response = $falAi->model('fal-ai/flux/schnell')
    ->prompt('A beautiful landscape')
    ->sync() // Switch to sync mode
    ->run();

// Returns the complete result immediately

$response = $falAi->model('fal-ai/flux/schnell')
    ->withWebhook('https://myapp.com/webhooks/fal')
    ->prompt('A beautiful sunset over mountains')
    ->imageSize('landscape_4_3')
    ->run();

// Returns: ['request_id' => 'req_123...', 'status' => 'IN_QUEUE']

// This route is automatically registered by the package
// POST /webhooks/fal

// Use it in your requests:
$response = $falAi->model('fal-ai/flux/schnell')
    ->withWebhook(url('/webhooks/fal')) // Uses the built-in route
    ->prompt('Your prompt here')
    ->run();

use FalAi\Middleware\VerifyFalWebhook;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/webhooks/fal', function (Request $request) {
    $payload = $request->json()->all();
    
    if ($payload['status'] === 'COMPLETED') {
        $images = $payload['data']['images'];
        // Process successful results
        foreach ($images as $image) {
            // Save image URL: $image['url']
        }
    } elseif ($payload['status'] === 'FAILED') {
        $error = $payload['error'];
        // Handle error
    }
    
    return response()->json(['status' => 'processed']);
})->middleware(VerifyFalWebhook::class);

use FalAi\Middleware\VerifyFalWebhook;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;

Route::post('/webhooks/fal-custom', function (Request $request) {
    $payload = $request->json()->all();
    
    if ($payload['status'] === 'COMPLETED') {
        $images = $payload['data']['images'];
        // Process successful results
        foreach ($images as $image) {
            // Save image URL: $image['url']
            // Custom processing logic here
        }
    } elseif ($payload['status'] === 'FAILED') {
        $error = $payload['error'];
        // Handle error with custom logic
    }
    
    return response()->json(['status' => 'processed']);
})->middleware(VerifyFalWebhook::class);

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

Route::post('/webhooks/fal-manual', function (Request $request) {
    $verifier = new WebhookVerifier();
    
    try {
        $verifier->verify($request);
        
        // Webhook is valid, process payload
        $payload = $request->json()->all();
        
        return response()->json(['status' => 'verified']);
        
    } catch (WebhookVerificationException $e) {
        return response()->json([
            'error' => 'Unauthorized',
            'message' => 'Webhook verification failed'
        ], 401);
    }
});

return [
    'api_key' => env('FAL_API_KEY'),
    'base_url' => 'https://queue.fal.run',
    'default_model' => '',
    
    'webhook' => [
        // JWKS cache TTL in seconds (max 24 hours)
        'jwks_cache_ttl' => env('FAL_WEBHOOK_JWKS_CACHE_TTL', 86400),
        
        // Timestamp tolerance in seconds (prevents replay attacks)
        'timestamp_tolerance' => env('FAL_WEBHOOK_TIMESTAMP_TOLERANCE', 300),
        
        // HTTP timeout for JWKS fetching
        'verification_timeout' => env('FAL_WEBHOOK_VERIFICATION_TIMEOUT', 10),
    ],
];

$request = $falAi->model('fal-ai/flux/schnell')
    ->prompt('Your prompt here')           // Set the text prompt
    ->imageSize('landscape_4_3')           // Set image dimensions
    ->numImages(2)                         // Number of images to generate
    ->seed(12345)                          // Set random seed
    ->withWebhook('https://...')           // Add webhook URL
    ->queue()                              // Use queue mode
    ->sync();                              // Use sync mode

use FalAi\Exceptions\WebhookVerificationException;
use InvalidArgumentException;

try {
    $response = $falAi->model('fal-ai/flux/schnell')
        ->withWebhook('https://myapp.com/webhook')
        ->prompt('Test prompt')
        ->run();
        
    if (!$response->successful()) {
        throw new Exception('API request failed: ' . $response->body());
    }
    
} catch (InvalidArgumentException $e) {
    // Invalid webhook URL or other validation errors
    echo "Validation error: " . $e->getMessage();
} catch (WebhookVerificationException $e) {
    // Webhook verification failed (in webhook endpoints)
    echo "Webhook error: " . $e->getMessage();
} catch (Exception $e) {
    // Other errors (network, API, etc.)
    echo "Error: " . $e->getMessage();
}
bash
php artisan vendor:publish --provider="FalAi\FalAiServiceProvider"