我正在尝试为注册用户制作个人资料页面。 在此页面上将显示Auth \ User数据(姓名,电子邮件),但也会显示额外的个人资料信息(城市,国家/地区,电话号码等)。
我已经建立了一对一的关系,但我遇到了一个问题。 创建用户后,我希望自动为该特定用户创建配置文件。
目前,我只是通过修补程序为我的第一个用户添加了个人资料,但是一旦我创建了第二个用户&去了个人资料页面,它给出了一个错误(看到配置文件尚未制作)。
在Profile.php中我有:
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Profile extends Model {
protected $table = 'profiles';
protected $fillable = ['city', 'country', 'telephone'];
public function User()
{
return $this->belongsTo('App\User');
}
}
在User.php中我添加了:
<?php namespace App;
...
class User extends Model implements AuthenticatableContract, CanResetPasswordContract {
use Authenticatable, CanResetPassword;
...
protected $table = 'users';
protected $fillable = ['name', 'lastname', 'email', 'password'];
protected $hidden = ['password', 'remember_token'];
public function Profile()
{
return $this->hasOne('App\Profile');
}
}
我像这样显示个人资料数据(在我的profile.blade.php页面上):
Full name: {{ Auth::user()->name }} {{ Auth::user()->lastname }}
E-Mail Address: {{ Auth::user()->email}}
City: {{ Auth::User()->profile->city}}
Country: {{ Auth::User()->profile->country}}
Phone number: {{ Auth::User()->profile->telephone}}
我猜我需要在'AuthenticatesAndRegistersUsers'特性和'Registrar.php'服务中添加一些内容,但我不知道是什么。
谢谢,
塞德里克
答案 0 :(得分:3)
正如您对问题的评论所述,我认为这里最好的答案是将两个模型合并为一个用户模型。
但是,如果您想在创建用户时创建关系,则可以修改注册商服务。
AuthenticatesAndRegistersUsers
特征将使用注册商(默认情况下位于app/Services/Registrar.php
)来验证和注册用户。
您可以修改其中的create
方法,以便同时自动创建配置文件关系:
public function create(array $data)
{
$user = User::create([
'name' => $data['name'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
$user->profile()->save(new Profile);
return $user;
}
答案 1 :(得分:2)
我想到了三种选择。
为什么要将用户帐户与个人资料分开?我想不出一个很好的理由(不是说没有一个,我只是想不到一个)。组合表可以节省数据库查询并完全解决此问题。我认为这是最好的选择。
在User :: created事件上创建一个侦听器。
User::created(function(User $user) {
$user->profile->save(Profile::create([... ]));
});
创建用户存储库以管理所有数据库查询。然后在存储库创建方法中,您可以手动创建配置文件记录并将两者关联起来。然后直接使用注册器中的存储库而不是模型