Reputation: 349
I'm trying to save an employee number as EMP00001 format. I have the following code that I'm using in the controller under store and I'm getting an error of A non-numeric value encountered.
$emp = Employee::create($request->all()+
['employee_number' => Employee::max('employee_number') + 1 ]);
$employee_code = sprintf ("EMP",'%06d');
$employee_no = ($employee_code +$emp);
$employee_no->save();
MySQL column for employee_number is varchar. Can anyone see what I'm doing wrong?
Upvotes: 0
Views: 127
Reputation: 3757
It throws such error, because Employee::max('employee_number')
returns a string, it is varchar column type, since you are inserting them in format of EMP00001
.
You have set strict type for PHP which is good.
Try to call it outside the main Query, extract the number, add number to it and do the insertion:
$num_employee_max = Employee::max('employee_number');
$num_employee = (int)str_replace('EMP', '', $num_employee_max);
$new_num_employee = $num_employee + 1;
$employee_code = sprintf('EMP%06d',$new_num_employee);
$sanitized values = $request->all(); //do the proper sanitization instead of this
$emp = Employee::create( $sanitized values +
['employee_number' => $employee_code]);
Note: Avoid inserting non-sanitized values from input directly in database.
Also, sprintf ("EMP",'%06d'); doesn't do a thing. see about sprintf: http://php.net/manual/en/function.sprintf.php
Upvotes: 2
Reputation: 1354
try
$emp = Employee::create(array_collapse([
$request->toArray(),
['employee_number' => preg_replace("|(\d+)|e",
"$1+1",Employee::max('employee_number'))]
]));
$employee_code = sprintf ("EMP",'%06d');
$employee_no = ($employee_code +$emp);
$employee_no->save();
Upvotes: 1