Skip to content

How To Send Image Data In Laravel API Tests

When writing Laravel API tests, postJson() is indispensable. For sending image data as a payload, there is no postRaw(). This shows how to test your API with image data as a payload in Laravel.

Coding on a laptop. A person typing code and working on development for their business.

The available API methods are coded in ways that aren’t suitable for raw data payloads. postJson() and even post() type hint the data argument as an array, and both forward data as the parameter argument to call().

This snippet shows how you can leverage the underlying call() method available in Laravel’s PHPUnit TestCase class. Pest users, note that tests implicitly extend TestCase.

 * This is run within a test.

$payload = file_get_contents('path/to/image.png');

    [], // Parameters
    [], // Cookies
    [], // Files
    [   // Server
        'HTTP_CONTENT_LENGTH' => mb_strlen($payload, '8bit'),      
        'CONTENT_TYPE'        => 'image/*',
        'HTTP_ACCEPT'         => 'application/json'
); // Assertions can be chained as usual