Nice and fluent way to create truly unique codes or tokens.
Require the package from Composer:
composer require thejawker/super-random
As of Laravel 5.5 it will magically register the package.
Just simple call the generate method on SuperRandom Facade or the handy shortcut helper function.
$code = SuperRandom::generate();
echo $code; //
$code = superRandom();
Often you don't want more than one of the same codes or tokens to be present in your database. Although it's easy to compare to the database it is annoying having to re-implement this all over the place.
By specifying the table.column
in the for
method you can easily make it entry aware.
ConcertTicket::create([
'band' => 'DYSSEBIA',
'code' => SuperRandom::for(ConcertTicket::class)->generate()
]);
// Or more explicit:
ConcertTicket::create([
'band' => 'DYSSEBIA',
'code' => SuperRandom::for('concerts.code')->generate()
]);
You can specify the length as follows:
ConcertTicket::create([
'band' => 'DYSSEBIA',
'code' => SuperRandom::length(12)->generate()
]);
You can specify the allowed chars as follows:
ConcertTicket::create([
'band' => 'DYSSEBIA',
'code' => SuperRandom::chars('abc123')->generate()
]);
By default we only include numbers and UPPERCASE characters with the exclusion of: 1, I, O, 0
since they look a lot alike and you don't want your users to guess.
You can alternatively set the config right on the generate()
method.
ConcertTicket::create([
'band' => 'DYSSEBIA',
'code' => SuperRandom::generate([
'table' => 'concerts',
'column' => 'code',
'length' => 15,
'chars' => 'abc123'
])
]);
composer test
The MIT License (MIT). Please see License File for more information.