This commit is contained in:
Bozhidar Slaveykov 2024-04-04 15:17:07 +03:00
parent a6103f3d56
commit 77a6861722
2 changed files with 54 additions and 4 deletions

View file

@ -28,8 +28,13 @@ class CustomerResource extends Resource
{
return $form
->schema([
Forms\Components\TextInput::make('name'),
Forms\Components\TextInput::make('email'),
Forms\Components\TextInput::make('name')
->required(),
Forms\Components\TextInput::make('email')
->email()
->unique('customers', 'email')
->required(),
Forms\Components\TextInput::make('phone'),
Forms\Components\TextInput::make('address'),
Forms\Components\TextInput::make('city'),
@ -38,7 +43,6 @@ class CustomerResource extends Resource
Forms\Components\TextInput::make('country'),
Forms\Components\TextInput::make('company'),
]);
}

View file

@ -4,12 +4,12 @@ namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Str;
class Customer extends Model
{
use HasFactory;
protected $fillable = [
'name',
'email',
@ -21,4 +21,50 @@ class Customer extends Model
'country',
'company',
];
public static function boot()
{
parent::boot();
static::created(function ($model) {
if (strlen($model->name) > 5) {
$generateUsername = static::generateUsername($model->name, $model->id);
} elseif (strlen($model->email) > 5) {
$generateUsername = static::generateUsername($model->email, $model->id);
} else {
$generateUsername = static::generateUsername(Str::random(10), $model->id);
}
$this->username = $generateUsername;
$this->save();
});
}
public static function generateUsername($fullName)
{
$removedMultispace = preg_replace('/\s+/', ' ', $fullName);
$sanitized = preg_replace('/[^A-Za-z0-9\ ]/', '', $removedMultispace);
$lowercased = strtolower($sanitized);
$splitted = explode(" ", $lowercased);
if (count($splitted) == 1) {
$username = substr($splitted[0], 0, rand(3, 6)) . rand(111111, 999999);
} else {
$username = $splitted[0] . substr($splitted[1], 0, rand(0, 4)) . rand(11111, 99999);
}
$maxLen = 16;
if (strlen($username) > $maxLen) {
$username = substr($username, 0, $maxLen);
}
return $username;
}
}