Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

KarolGil's avatar

Laravel - InvalidArgumentException: Malformed UTF-8 characters

Hi,

Has anyone encountered such a mistake?

// Coding of the phpmyadmin database: utf8mb4_general_ci
// Database connection in phpmyadmin: utf8_unicode_ci
// Settings in Laravel:

'mysql' => [
    'driver' => 'mysql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => 'ai_',
    'prefix_indexes' => true,
    'strict' => false,
    'engine' => null,
    'options' => extension_loaded('pdo_mysql') ? array_filter([
        PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
    ]) : [],
],

Controller:

$newData = $this->getOffersList($data, $request);

//  dd( mb_detect_encoding ( $newData[0]['description'] )); // "ASCII"

return response()->json([
    'error'=>false,
    'offers'=> $newData
]);

Error:

InvalidArgumentException: Malformed UTF-8 characters, possibly incorrectly encoded in file /var/www/vendor/laravel/framework/src/Illuminate/Http/JsonResponse.php on line 75

The database offers in, inter alia, the following languages: English, Polish, Ukrainian etc.

0 likes
6 replies
Sinnbeck's avatar

Does this happen if you get just a single record?

$newData = MyModel::first();
KarolGil's avatar

@sinnbeck Depending on the records and parameters in the query. It works once and once it doesn't.

Sinnbeck's avatar

So it would seem that there maybe a single record that is causing the issue?

KarolGil's avatar
KarolGil
OP
Best Answer
Level 9
        return response()->json([
            'error'=>false,
            'offers'=> $newData
        ], 200, [], JSON_INVALID_UTF8_SUBSTITUTE );

// and

$offer->user->surname = trim( mb_substr ( $offer->user->getOriginal('surname'), 0, 1, 'UTF-8') );

Please or to participate in this conversation.