I am generating customer IDs for each customer after they make an order in a Laravel 5 application. What follows is the code to generate an ID for the customer, which is composed of part of their first name, last name, and if this renders a duplicate, a random string is appended.
$ID = strtolower(substr($itemsP['firstName'],0,2) . $itemsP['lastName']);
function checkforduplicateID($iD,$firstName,$lastName)
{
$f = $firstName;
$l = $lastName;
$orders = Order::where('customerID',$iD)->get()->count();
if($orders>0)
{
$ID = strtolower(substr($firstName,0,2) . $lastName . substr(md5(rand()),0,2));
checkforduplicatecode($ID,$f,$l);
}
else
{
return $iD;
}
}
$sessionOrder->customerID = checkforduplicateID($ID,$itemsP['firstName'],$itemsP['lastName']);
$sessionOrder->save();
On the first go around (no duplicate) this works perfectly. But as soon as I have two customers with the same first and last name, the function returns a null rather than the same ID with an appended (and random) string.
So I am getting an integrity violation on the second to last line because I am inserting a null into my database.
Something is obviously wrong with my checkforduplicateID function, but I can't figure out what.
Please assist.