Michael Emerson
Michael Emerson

Reputation: 1813

Laravel cannot get response to parse foreign characters correctly

After searching for a suitable answer, I find that the solutions people offer do not work so I am posting here in the hope of some help.

I have a database of users that will list by first letter of name in a directory. However there is one user that breaks the results because their name begins with a letter with a foreign character, namely Á.

I get the user results with:

$users = $this->users->getAll($params);

And then return the response using collection which json encodes it:

return response()->collection($users);

But I get the following error if the above user is returned in results:

The Response content must be a string or object implementing __toString(), 'boolean' given.

I've tried using the JSON_UNESCAPED_UNICODE option, like many people suggest in solutions, like this:

return response()->json($users, 200, ['Content-type'=> 'application/json; charset=utf-8'], JSON_UNESCAPED_UNICODE);

but it turns out the response isn't coming back as UTF-8 after attempting to log it. However, as far as I can tell, the database is UTF-8 encoded so I don't understand what's happening here.

The problem is, even if I was to change the character to a regular A, there could still be future users with foreign characters in their name, and I'd rather there be something in place to handle this.

Any help is appreciated.

Upvotes: 0

Views: 240

Answers (2)

Saibal Roy
Saibal Roy

Reputation: 431

In config/database.php :

'mysql' => [
        'driver' => 'mysql',
        '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' => '',
        'strict' => false,
        'engine' => null,
    ],

And now make the columns collation as : utf8mb4_unicode_ci. Hope this works. Thanks.

Upvotes: 0

Md Nasir Fardoush
Md Nasir Fardoush

Reputation: 820

collation utf8mb4_unicode_ci works fine for me.
If you mention your database collation it's define your issue more readable.

Upvotes: 1

Related Questions