metalogico / laravel-mocka
Laravel Mocka provides fake API responses to designated users while serving real data to everyone else. A drop-in replacement for Laravel's Http facade, perfect for app store submissions, demos, and testing without disrupting production traffic
Requires
- php: ^8.0
- laravel/framework: ^9.0|^10.0|^11.0|^12.0
- laravel/prompts: ^0.3.6
Requires (Dev)
- orchestra/testbench: ^10.4
- pestphp/pest: ^3.8
- pestphp/pest-plugin-laravel: ^3.2
This package is auto-updated.
Last update: 2025-08-25 18:15:46 UTC
README
Laravel Mocka provides fake API responses to designated users while serving real data to everyone else. A drop-in replacement for Laravel's Http facade, perfect for app store submissions, demos, and testing without disrupting production traffic.
Why Mocka?
When your Laravel app calls external APIs (like DMS, MES, or any third-party service), you often need to provide mock responses for:
- ๐ App Store Reviews - Apple and Google reviewers need working apps without real API access
- ๐งช Testing Environments - Stable, predictable responses for your test suite
- ๐ฅ Demo Users - Showcase your app without depending on external services
- ๐ Development - Work offline or with unstable external APIs
Features
- ๐ฏ User-specific mocking - Mock responses only for designated users
- ๐ Drop-in replacement - Use
MockaHttp
instead of Laravel'sHttp
facade - ๐ File-based mocks - Organize mock responses in PHP files
- ๐จ Response templating - Dynamic mock responses with Faker integration
- ๐ Request logging - Track which requests are mocked vs real
- โ Error simulation - Test failure scenarios easily
- ๐ฃ๏ธ Header activator - Enable/disable mocking via
X-Mocka
header - ๐ Force activation - Enable/disable mocking via
withOptions(['mocka' => true])
- ๐ Rate limiting simulation - Simulate slow APIs delays for testing
- ๐ Advanced URL matching - Regex, wildcards, and parameter matching (coming soon โข)
- โ Command Line tools - List mappings
- โก Zero performance impact - Only active for designated users
Installation
You can install the package via composer:
composer require metalogico/laravel-mocka
Publish the config file:
php artisan vendor:publish --tag="mocka-config"
Quick Start
1. Configure Mock Users
In your .env
file:
MOCKA_ENABLED=true MOCKA_USERS=reviewer@apple.com,tester@google.com,demo@yourapp.com MOCKA_LOGS=true
2. Create Mock Files
Create mock files in resources/mocka/
:
resources/mocka/api.mock.php
<?php return [ 'POST' => [ 'authenticate' => [ 'success' => true, 'user_id' => 12345, 'token' => 'mock_token_12345', 'expires_at' => time() + 3600, ], ], 'GET' => [ 'getFileList' => [ 'success' => true, 'files' => [ [ 'name' => 'file1.pdf', 'size' => 1024, 'created_at' => '2023-01-01 00:00:00', ], [ 'name' => 'file2.pdf', 'size' => 2048, 'created_at' => '2023-01-02 00:00:00', ], // ... ], ] ], ];
3. Configure URL Mappings
In config/mocka.php
:
'mappings' => [ [ 'url' => env('EXTERNAL_API_URL').'/api/authenticate', 'file' => 'api.mock.php', 'key' => 'POST.authenticate', ], [ 'url' => env('EXTERNAL_API_URL').'/api/files/', 'file' => 'api.mock.php', 'key' => 'GET.getFileList', ], ];
4. Use MockaHttp in Your Services
Replace Laravel's Http
facade with MockaHttp
:
<?php namespace App\Services; use Metalogico\Mocka\Facades\MockaHttp; class DmsService { public static function authenticate($user, $password) { $response = MockaHttp::post(config('external_api_url').'/api/authenticate', [ 'user' => $user, 'password' => $password, ]); session()->put('token', $response->json()['token']); return $response->json(); } public static function getFileList() { $response = MockaHttp::withHeaders([ 'Authorization' => 'Bearer '.session()->get('token'), ])->get(config('external_api_url').'/api/files'); return $response->json(); } }
Advanced Features
Response Types: Static, Dynamic, or Hybrid
Mocka supports three approaches for mock responses:
Static Responses
Perfect for app store reviews and basic demos:
return [ 'GET' => [ 'simpleAuth' => [ 'success' => true, 'token' => 'static_token_123', 'user_id' => 12345, ], ], ];
Dynamic Responses
For complex testing with varying data:
return [ 'GET' => [ 'userList' => fn() => [ 'users' => collect(range(1, fake()->numberBetween(3, 8))) ->map(fn() => [ 'name' => fake()->name, 'email' => fake()->email, ]), 'total' => fake()->numberBetween(50, 200), ], ], ], ];
Hybrid Responses
You can even mix static and dynamic data as needed:
return [ 'GET' => [ 'mixedResponse' => fn() => [ 'status' => 'success', // Static 'timestamp' => time(), // Static but with function 'dynamic_data' => fn() => [ 'user_count' => fake()->numberBetween(5, 20), 'featured_products' => collect(range(1, 3)) ->map(fn() => [ 'id' => fake()->numberBetween(1000, 9999), 'name' => fake()->words(3, true), 'price' => fake()->randomFloat(2, 10, 500), ]), ], ], ], ], ];
Advanced URL Matching
Configure sophisticated URL matching patterns:
'mappings' => [ // Exact match [ 'url' => 'https://api.example.com/users/123', 'match' => 'exact', // which is the default 'file' => 'users.mock.php', 'key' => 'GET.specificUser', ], // Wildcard matching [ 'url' => 'https://api.example.com/users/*', 'match' => 'wildcard', 'file' => 'users.mock.php', 'key' => 'GET.anyUser', ], // Regex matching (coming soom โข) [ 'url' => '/^https:\/\/api\.example\.com\/orders\/\d+$/', 'match' => 'regex', 'file' => 'orders.mock.php', 'key' => 'GET.orderDetail', ], ];
Error Simulation
Simulate API errors by defining error configurations in your mappings:
'mappings' => [ [ 'url' => 'https://api.example.com/users/123', 'file' => 'users.mock.php', 'key' => 'GET.specificUser', 'errors' => 'GET.specificUserErrors' // Optional error configuration ], ];
Define error responses in your mock files:
return [ 'GET' => [ 'specificUser' => fn() => [ 'id' => fake()->numberBetween(1000, 9999), 'name' => fake()->name, 'email' => fake()->email, ], 'specificUserErrors' => [ 'error_rate' => 25, // 25% chance of error 'errors' => [ 422 => [ 'message' => 'Validation failed', 'errors' => ['name' => ['Name is required']] ], 404 => [ 'message' => 'User not found', 'code' => 'USER_NOT_FOUND', 'timestamp' => time() ], 503 => fn() => [ // Dynamic error responses 'message' => 'Service temporarily unavailable', 'retry_after' => fake()->numberBetween(30, 300), 'incident_id' => fake()->uuid, ], ], ], ], ];
Rate Limiting Simulation
Add delays to simulate slow APIs:
'mappings' => [ [ 'url' => 'https://slow-api.com/data', 'file' => 'slow.mock.php', 'key' => 'GET.slowResponse', 'delay' => 5000, // 5 second delay ], ];
Jobs and Artisan (Force Activation)
When running inside queued Jobs or Artisan commands (where there is no web request/user), you can explicitly enable Mocka per request using options:
use Metalogico\Mocka\Facades\MockaHttp; $enabled = ($user === 'reviewer@apple.com') ? true : false; $response = MockaHttp::withOptions(['mocka' => $enabled]) ->get(config('external_api_url').'/api/files');
Notes:
- Mocka must still be enabled and allowed in the current environment/host by config.
- If the current user is in
MOCKA_USERS
, forcing is not required (it's always active). - You can also use the
X-Mocka
header in regular request contexts to activate per-call.
Artisan Commands
List Mock Mappings
List all configured mappings and whether they correctly resolve to a mock file/key. The output uses a compact, two-line layout per mapping:
php artisan mocka:list
Per mapping you will see two rows:
- Main row โ shows mapping details and overall Status for file/key resolution.
- Sub-row โ shows the
errors
key (or-
if none) in thekey
column, and its validation result instatus
.
Configuration
The configuration file config/mocka.php
supports these options:
return [ // Globally enable Mocka (default: false in production) 'enabled' => env('MOCKA_ENABLED', false), // Enable request logging (default: true in development) 'logs' => env('MOCKA_LOGS', true), // Users that get mocked responses 'users' => array_filter(explode(',', env('MOCKA_USERS', ''))), // Path to mock files 'mocks_path' => resource_path('mocka'), // Default delay for all mocked requests (milliseconds) 'default_delay' => 0, // Security: only allow mocking for these hostnames (empty => all hosts allowed) 'allowed_hosts' => [], // Allowed application environments for Mocka activation (default: local only) // Extend this to enable in other envs, e.g. ['local', 'staging'] 'environments' => ['local'], // URL mappings 'mappings' => [ // Your API mappings here ], ];
- allowed_hosts: restricts Mocka activation to specific upstream hosts; leave empty to allow all.
- environments: restricts activation to these Laravel environments (default ['local']).
How It Works
- Activation Check: If enabled and allowed by environment/host, Mocka checks activation triggers in order: user allowlist,
withOptions(['mocka' => true])
, orX-Mocka
header - URL Matching: If the user should be mocked, it matches the request URL against the configured mappings
- Mock Loading: Loads the appropriate mock file and extracts the response using dot notation
- Template Processing: Processes any template variables (faker, time functions, etc.)
- Response Simulation: Returns the mock response with optional delays or errors
- Logging: Logs whether the request was mocked or passed through
Testing
composer test
Security
If you discover any security related issues, please email metalogico@gmail.com instead of using the issue tracker.
License
The MIT License (MIT). Please see License File for more information.
Made with โ in Italy