Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 eloquent not storing special characters in database

I am using laravel 5.2 and here are my database configuration settings:

'charset' => 'utf8',
'collation' => 'utf8_general_ci',

I have also tried 'utf8_unicode_ci' as collation but its also not working.

Use case: This is the text I am trying to insert:

$str = "Après 9 mois passés dans le"

but this is storing:

Après 9 mois passés dans le
like image 278
Maha Dev Avatar asked Oct 29 '22 03:10

Maha Dev


1 Answers

What you're seeing there is the text being replaced with HTML entities this usually is the result of text coming directly from an HTML source (either a form with text that was previously converted to htmlentities or an other source).

The ideal solution here is to ensure that the text is not received as HTML entity encoded, however if this is not an option (which it very often is not), you can use:

 $decoded = html_entity_decode($text); 

to decode the entities into their actual characters before you insert them.

A bit of trivia:

You don't actually need to encode all characters to their corresponding entities to display on HTML as long as you're properly sending Unicode text. This is why PHP has 2 different functions htmlspecialchars and htmlentities where the first function only encodes what is necessary to encode in order to not break HTML (those 5 characters listed in the manual, <, >, &, " and ') while the second one encodes everything based on the linked table.

like image 161
apokryfos Avatar answered Nov 15 '22 06:11

apokryfos