注册新用户时,我希望他们选择一个唯一的用户名。当我使用 Jetstream 时,一切都使用用户名,但是当我使用 Laravel Fortify 和 Laravel UI 重建时,无论用户在字段中输入什么,用户名都是空的。下面我包含了几个用于添加和注册用户名的代码示例。
我在调试或日志中没有收到任何错误以支持任何已知问题。
Register.blade.php(用户名输入)
<div class="px-2">
<x-general.form.label for="username" label="{{ __('Username') }}" class="" />
<x-general.form.input type="text" name="username" class="@error('username') is-invalid @enderror" value="" />
@error('username')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
@enderror
</div>
App\Actions\Fortify\CreateNewUser.php(创建函数)
public function create(array $input)
{
Validator::make($input, [
'name' => ['required', 'string', 'max:255'],
'username' => ['required', 'string', 'max:16'],
'email' => [
'required',
'string',
'email',
'max:255',
Rule::unique(User::class),
],
'password' => $this->passwordRules(),
])->validate();
return User::create([
'name' => $input['name'],
'username' => $input['username'],
'email' => $input['email'],
'password' => Hash::make($input['password']),
]);
}
用户模型
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name', 'email', 'password', 'username',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
创建用户表迁移
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->string('username')->unique();
$table->string('avatar')->nullable();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
用户工厂
<?php
namespace Database\Factories;
use App\Models\User;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Str;
class UserFactory extends Factory
{
/**
* The name of the factory's corresponding model.
*
* @var string
*/
protected $model = User::class;
/**
* Define the model's default state.
*
* @return array
*/
public function definition()
{
return [
'name' => $this->faker->name,
'username' => $this->faker->unique()->userName,
'email' => $this->faker->unique()->safeEmail,
'email_verified_at' => now(),
'password' => '$2y$10$92IXUNpkjO0rOQ5byMi.Ye4oKoEa3Ro9llC/.og/at2.uheWG/igi', // password
'remember_token' => Str::random(10),
];
print_r($this->faker->unique()->userName);
exit;
}
}
我无法弄清楚为什么没有提交用户名。这与我在基于 Jetstream 的项目中使用的代码完全相同。
任何帮助都是美妙的和感激的!