php - 如何使 RegisterController 的 create 方法在 Laravel 5 中生成 Profile 条目
问题描述
用户的详细信息存储在两个单独的表User
和Profile
.
我正在使用 Laravel 的内置身份验证,即:
php artisan make:auth
一旦用户注册,我希望除了创建一个User
条目之外,还会创建一个随附的Profile
条目(所有值都设置为 null)并User
通过 FK 链接到该条目。
然后用户被重定向到一个页面,他可以在其中填写Profile
详细信息。
// create_users_table.php
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
// create_profiles_table.php
Schema::create('profiles', function (Blueprint $table) {
$table->integer('user_id')->unsigned()->nullable();
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
$table->date('date_of_birth');
$table->string('city');
});
我猜想在调用's函数Profile
时必须实例化并保存相应的对象。RegisterController
create
protected function create(array $data)
{
return User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
在哪里创建和保存相应的 Profile 对象?
这个问题已经被问过了。一位成员建议对 进行更改app/Services/Registrar.php
,但 Laravel 5.4.0 似乎没有上述文件。有谁知道他所指的等效代码可以在 5.4.0 中找到吗?
解决方案
首先,为了让事情更容易,让我们profile()
在用户模型中定义关系。所以,在 中App\User
,你会有这样的东西。
public function profile()
{
return $this->hasOne(Profile::class);
}
我假设用户只有一个配置文件。如果他们有很多,请相应地更新关系。
然后,在 中App\Http\Controllers\Auth\RegisterController
,您将像这样覆盖该create()
方法:
protected function create(array $data)
{
$user = User::create([
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
// Creates the user profile
$profile = Profile::create([
//
]);
// Associates the relationship
$user->profile()->save($profile);
// This, of course, assumes you have
// the above relationship defined in your user model.
return $user;
}
或者,您可以挂钩到用户的模型事件。在你的App\User
类的boot()
方法中,你会有这样的东西。
public static function boot()
{
parent::boot();
static::created(function ($user)) {
$profile = Profile::create([
//
]);
$user->profile()->save($profile);
});
}
现在,每次创建用户时,都会关联相应的配置文件。
推荐阅读
- python - 多行字符串到字典
- swift - UIDatePicker 仅显示特定日期
- php - PHP在导入csv时获取准确的记录数
- warnings - useEffect/lint 警告会导致网页无法出现
- cmake - CPack NuGet 警告 NU5119 NoDefaultExcludes
- php - 在 PHP 和 HTML 之间传递多个参数
- macos - 缩放后Mojave vs Catalina上的NSTextView宽度不同
- python - 根据连续性创建熊猫数据框的子集
- php - 为什么 var_dump 在 php 代码中返回 null?
- c - GCC 是否具有检测 use-after-free 错误的功能?