Ideal way to generate a unique reference code?

Published 11 months ago by MyLibrary

Hey guys, I would like to generate a unique reference code in my system for Orders, Procurement and Transactions. Do you have any suggestions how big should be the reference code and how should I implement it in an efficient way? The system should have xxx procurement per year, xxxx orders per year and about xxxx transactions per year.

Thanks for your help!

11 months ago (868,375 XP)

can you just use the primary key from each model? Do you have to ensure the numbers are contiguous?


Hey @Snapey , Yes, I absolutely can, but I need the reference code to be something unique so I can also use in external platforms. (External service providers such as shipping carriers and so on).



Does it have to increment, in a order that makes sense?

If no then you can look into Ramset\Uuid

If you want the increment to make sense, you could do a prefix and then the ID as Snapey is saying.


@cawex, It does have also a regular Id (incremental Id) but also need a reference id.

That looks nice, but might need something a bit shorter. I've used the uniqid() function, do you think it is strong enough guys?



So if it's a really small application I think you are safe, but I would not recommend it, PHP's uniqid() is not actually unique, see their here:


Can't you do something like:


so you have a prefix, but it increment on the prefix, if it make sense. You could probably achieve this with substr()


how about just using bcrypt() on a random string and request rule reference code being unique? check if it's unique, if not, get a random string again and bcrypt it.


@cawex, I can use a validation to check if it unique, otherwise creating a new uniqid(). The prefix suggestion will create different size reference code with time, and I would prefer to keep it at the same length at this moment.

@Talky, that idea might work, but bcrypt generates a long reference code.

I wonder if there is something not too short and not too long that will include the microtime, the model type (for example order) and the model id, and then make a unique string out of that, what do you think guys?

At this moment I'm using:

strtoupper(uniqid('OR')) // OR stands for Orders prefix.

Thanks for your help guys!


@MyLibrary No it wouldn't as long as you don't go over that high a number else choose to have 10 digits.

11 months ago (868,375 XP)

I'm still unsure if you need it to be incremental?

Are you wanting it to be 'random' so that it cannot be guessed, or sequential like a an invoice number INV00001, INV00002 etc

If random then you could use a separate table, pre-populated with random reference numbers (all unique). Using transactions, take the next number and store what it was used for (entity and id) ?

Does it need to be a number? Could you use the hashids package?

Please sign in or create an account to participate in this conversation.