向用户添加属性
如果你需要为用户添加新的属性,例如电话号码、员工或学校 ID 等,一种方法是向 `users` 表中添加列。
创建迁移文件
创建一个迁移文件来添加新列。
你可以使用 `spark` 命令轻松地为其创建一个文件
php spark make:migration AddMobileNumberToUsers
并编写代码来添加/删除列。
<?php
namespace App\Database\Migrations;
use CodeIgniter\Database\Forge;
use CodeIgniter\Database\Migration;
class AddMobileNumberToUsers extends Migration
{
/**
* @var string[]
*/
private array $tables;
public function __construct(?Forge $forge = null)
{
parent::__construct($forge);
/** @var \Config\Auth $authConfig */
$authConfig = config('Auth');
$this->tables = $authConfig->tables;
}
public function up()
{
$fields = [
'mobile_number' => ['type' => 'VARCHAR', 'constraint' => '20', 'null' => true],
];
$this->forge->addColumn($this->tables['users'], $fields);
}
public function down()
{
$fields = [
'mobile_number',
];
$this->forge->dropColumn($this->tables['users'], $fields);
}
}
运行迁移
运行迁移文件
php spark migrate
并检查 `users` 表
php spark db:table users
创建 UserModel
请参阅 自定义用户提供程序。
不要忘记将添加的属性添加到 `$allowedFields` 属性中。
更新验证规则
你需要更新注册的 验证规则。
如果你不为新字段添加验证规则,则新字段数据将不会保存到数据库中。
在 **app/Config/Validation.php** 中添加包含所有注册验证规则的 `$registration` 属性
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
use CodeIgniter\Validation\StrictRules\CreditCardRules;
use CodeIgniter\Validation\StrictRules\FileRules;
use CodeIgniter\Validation\StrictRules\FormatRules;
use CodeIgniter\Validation\StrictRules\Rules;
class Validation extends BaseConfig
{
// ...
// --------------------------------------------------------------------
// Rules
// --------------------------------------------------------------------
public $registration = [
'username' => [
'label' => 'Auth.username',
'rules' => [
'required',
'max_length[30]',
'min_length[3]',
'regex_match[/\A[a-zA-Z0-9\.]+\z/]',
'is_unique[users.username]',
],
],
'mobile_number' => [
'label' => 'Mobile Number',
'rules' => [
'max_length[20]',
'min_length[10]',
'regex_match[/\A[0-9]+\z/]',
'is_unique[users.mobile_number]',
],
],
'email' => [
'label' => 'Auth.email',
'rules' => [
'required',
'max_length[254]',
'valid_email',
'is_unique[auth_identities.secret]',
],
],
'password' => [
'label' => 'Auth.password',
'rules' => [
'required',
'max_byte[72]',
'strong_password[]',
],
'errors' => [
'max_byte' => 'Auth.errorPasswordTooLongBytes',
]
],
'password_confirm' => [
'label' => 'Auth.passwordConfirm',
'rules' => 'required|matches[password]',
],
];
}
自定义注册视图
-
在 **app/Config/Auth.php** 文件中更改 `register` 视图文件。
public array $views = [ // ... 'register' => '\App\Views\Shield\register', // ... ];
-
将文件 **vendor/codeigniter4/shield/src/Views/register.php** 复制到 **app/Views/Shield/register.php**。
-
自定义注册表单以添加新字段。
<!-- Mobile Number --> <div class="form-floating mb-2"> <input type="tel" class="form-control" id="floatingMobileNumberInput" name="mobile_number" autocomplete="tel" placeholder="Mobile Number (without hyphen)" value="<?= old('mobile_number') ?>"> <label for="floatingMobileNumberInput">Mobile Number (without hyphen)</label> </div>