Reputation: 228
In my laravel app, I am working on a controller with two functions for adding users to the database (superfluous code excluded).
The first function takes input from a form and creates a single user:
public function addSingleUser() {
$first_name = Input::get('firstName');
$last_name = Input::get('lastName');
$email = Input::get('email');
$password = str_random(6);
$user = new User();
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->email = $email;
$user->password = Hash::make($password);
$user->save();
}
The second function reads in data from a csv and creates multiple users:
public function addManyUsers() {
putenv("LANG=fr_FR.UTF-8");
$users = Input::file('users');
$file = fopen($users,"r");
while($info = fgetcsv($file, 4096)) {
$first_name = trim($info[0]);
$last_name = trim($info[1]);
$email = trim($info[2]);
$password = str_random(6);
$user = new User();
$user->first_name = $first_name;
$user->last_name = $last_name;
$user->email = $email;
$user->password = Hash::make($password);
$user->save();
}
fclose($file);
}
Since users' names can have special characters, I need to be able to store utf-8 characters in the database. If I use utf-8 characters in the first function (via form input), everything gets stored correctly in the users table. But, if I use utf-8 characters in the second function (via csv), the fields are not stored correctly and get truncated at the first special character (ex: "Michæl" is stored as "Mich").
I thought this might be a problem with fgetscsv() not reading the data in correctly, but when I tried data-dumping a field (ex: dd($first_name);
), the outputted string is correct, containing the special characters. The same is true if I try dd($user);
. So if the first function is able to save correctly to the database, I am confused on why the second is not?
Upvotes: 0
Views: 1172
Reputation: 983
Did you try opening your csv file in an editor and saving it with UTF-8 encoding ? Briefly, did you try encoding the csv itself?
Check UTF-8 part of this link for more information.
Best,
Upvotes: 1