0

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.

1 Answer 1

1

I believe that here

if($orders>0) {
    $ID = strtolower(substr($firstName,0,2) . $lastName . substr(md5(rand()),0,2));
    checkforduplicatecode($ID,$f,$l);
} else {

you need to return the new ID like this:

if($orders>0) {
    $ID = strtolower(substr($firstName,0,2) . $lastName . substr(md5(rand()),0,2));
    return checkforduplicateID($ID,$f,$l);
} else {
Sign up to request clarification or add additional context in comments.

5 Comments

I don't think that is correct, if there is more than zero matching orders nothing should be returned because the function needs to run again until no orders match, -and then- return the ID.
you're not looping like that...what does checkforduplicatecode() do? is that supposed to call the same function? even so, you'll need to return what it produces.
assuming that checkforduplicateID() was the intended self looping structure, i updated the solution.
Ah thank you. Did not realize I needed to return like that to get it to loop like I wanted. tips hat
tips hat in return

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.