Hello. Usually, I did not ask myself this question, but used the id of the object that was created by auto increment. That is, I searched for objects based on them, which is auto-increment $post = Post::find(1); . And I often noticed that in large applications they generate unique random identifiers for objects.

For example: if they create the first category, then its id (auto-increment) will be 1, and some kind of gid , pid , cid will be equal to 10254 . That's what it's called? And how to make a random but unique id generated for an object?

  • Honestly, I don’t know how it is with the best practitioners, but I somehow did it for myself, like this: I took the values ​​of all columns of a row (especially along with the added id and creation time), concocted it into a string, and from this I found a hash (for example, md5 ). - silksofthesoul
  • max() + 1 to help you - teran

2 answers 2

There is no sense in abandoning id in favor of other identifiers, unless the goal is to obfuscate data in relation to the outside world.

Then the UUID is used, or just an arbitrary string. Uniqueness is achieved by a low probability of collisions. Although the test also does not hurt, in the case of mysql on the field should hang the index UNIQUE, it also speeds up the sample. But not faster than the usual id selection.


In addition, if we are talking about a URL, then using a CNC is wiser. Usually this is just a name in transliteration.

site.name/post/generacija_unikalnogo_id

  • the point is that, when building a link of the site.name/post/1 type, site.name/post/1 would put not the auto-incremental ID, but the random one that the link would not show above for the first post (in the database), but what would be about site.name/post/205213 . - Alex_01
  • @ Alex_01 start autoincrement in the table table from 205212 :) - teran
  • one
    @ Alex_01, this is called obfustsirovat. Add the field code VARCHAR(36) NOT NULL to the table and write UUID() in it, hang the UNIQUE on it as it was said, and then search through the code field. Get site.name/post/b2f7f9d7-dd65-11e6-885b-c5cfbd441eca - Gedweb
  • @teran is not so interesting) - Alex_01
  • @Gedweb I don't want to use slug - Alex_01

You can use the regular PHP function: uniqid()

http://php.net/manual/ru/function.uniqid.php

And save in the database, in the uid field, for example, every time you save. When passing the second parameter to the function, a unique id will be sufficient. An example of the generated string:

587fd609b30903.05749207