Or
$myStr = str_random(60);
The example shown is with string length of 60 characters.
However don't think that this string necessarily is unique the probability of it not being unique is quite small though.
Using Laravel's String class :
Str::random(60)
https://github.com/laravel/framework/blob/4.2/src/Illuminate/Support/Str.php#L189
For when I need a string primary key, I use Str::quickRandom($length)
and check if it exists already before inserting, and loop around again if it does. I'm sure there are better approaches (UUID perhaps) but this works well enough. If your string length is too low, you'll probably start looping a lot until a non-existing key is found which isn't good, and could happen sooner than you'd expect.
The reason I use quickRandom is that it's quicker (as the name suggests) than "secure" random. We aren't using the generated strings for cryptography, so there's no worry.
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community