custom generatorConfig does not override GeneratesUsernames trait
bleuscyther opened this issue · 3 comments
It seems like all the configuration is taken from the config file but never over written
Can you post your generatorConfig
method? I've tried to duplicate the issue on my end but had no luck.
Hi @samueljtaylor ,
Thanks for your library.
Sorry for the short description.
Here is the generatorConfig method for one of my models
public function generatorConfig( Generator &$generator ) {
$generator->setConfig( [
'separator' => '_',
'unique' => true,
'model' => '\\App\\Team',
'column' => 'system_id'
] );
}
I also use a custom getName method :
public function getName()
{
return $this->normalized_name ?? (string)Uuid::generate(4);
}
The issue that i have is that when using the GeneratesUsernames Trait it does not try to save on the column i specified.
Maybe i am wrong but in line 14 and 28 of taylornetwork/laravel-username-generator/src/GeneratesUsernames.php
the column name is not overwritten :
...
if(!$model->getAttribute(config('username_generator.column', 'username'))) {
...
$this->attributes[config('username_generator.column', 'username')] = $generator->generate($this->getName());
I think that config('username_generator.column', 'username')
would be $generator->column
but $generator
is not available in the bootGeneratesUsernames
.
here is a change i propose :
public static function bootGeneratesUsernames()
{
static::saving(function ($model) {
$model->generateUsername();
});
}
public function generateUsername()
{
$generator = new Generator();
$this->generatorConfig($generator);
if(!$model->getAttribute($generator->column)) {
try {
$this->attributes[$generator->column] = $generator->generate($this->getName());
} catch (\Exception $e) {
// Failed but don't halt saving the model
}
}
}
I don't know how it will perform for large batch, it looks like it would be slower.
For my current specific use case, just to make sure i can handle big data, i use 2 different models. The second one is an extended version of the first but with the Trait. That way i test for the existing column before assigning the Class. (i still think its an overkill maybe saving just a few milliseconds 😂 )
Hi @bleuscyther
Thanks for the detailed response, I've added your changes to v2.2.2
Let me know if you have any other issues