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.
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
- 🎯 User-specific mocking - Mock responses only for designated users
- 🔄 Drop-in replacement - Use
MockaHttpinstead of Laravel'sHttpfacade - 📁 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-Mockaheader - 📝 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
You can install the package via composer:
composer require metalogico/laravel-mockaPublish the config file:
php artisan vendor:publish --tag="mocka-config"In your .env file:
MOCKA_ENABLED=true
MOCKA_USERS=reviewer@apple.com,tester@google.com,demo@yourapp.com
MOCKA_LOGS=trueCreate 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',
],
// ...
],
]
],
];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',
],
];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();
}
}Mocka supports three approaches for mock responses:
Perfect for app store reviews and basic demos:
return [
'GET' => [
'simpleAuth' => [
'success' => true,
'token' => 'static_token_123',
'user_id' => 12345,
],
],
];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),
],
],
],
];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),
]),
],
],
],
],
];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 soon ™)
[
'url' => '/^https:\/\/api\.example\.com\/orders\/\d+$/',
'match' => 'regex',
'file' => 'orders.mock.php',
'key' => 'GET.orderDetail',
],
];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,
],
],
],
],
];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
],
];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-Mockaheader in regular request contexts to activate per-call.
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:listPer mapping you will see two rows:
- Main row — shows mapping details and overall Status for file/key resolution.
- Sub-row — shows the
errorskey (or-if none) in thekeycolumn, and its validation result instatus.
The configuration file config/mocka.php supports these options:
return [
// Globally enable Mocka (default: false in production)
'enabled' => env('MOCKA_ENABLED', false),
// Basic logging (can be extended later)
'logs' => env('MOCKA_LOGS', false),
// Users (emails) for which Mocka is active when enabled
// Supports comma-separated env var: MOCKA_USERS="apple@example.com, foo@bar.com"
'users' => array_values(array_filter(array_map('trim', 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']).
- Activation Check: If enabled and allowed by environment/host, Mocka checks activation triggers in order: user allowlist,
withOptions(['mocka' => true]), orX-Mockaheader - 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
composer testIf you discover any security related issues, please email metalogico@gmail.com instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.
Made with ☕ in Italy