我正在尝试为我的注册用户制作个人资料页面。 在此页面上,将显示 Auth\User 数据(姓名、电子邮件)以及额外的个人资料信息(城市、国家、电话号码等)。
我已经建立了一对一的关系,但我遇到了一个问题。 创建用户后,我想自动为该特定用户创建一个配置文件。
目前我只是通过 tinker 为我的第一个用户添加了个人资料,但是当我创建第二个用户并转到个人资料页面时,它给出了一个错误(看到个人资料尚未创建)。
在 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”服务添加一些内容,但我不知道是什么。
谢谢,
塞德里克
最佳答案
正如在对您的问题的评论中指出的,我认为这里最好的答案是将两个模型合并为一个用户模型。
但是,如果您想在用户创建时创建关系,您可以修改 Registrar 服务。
AuthenticatesAndRegistersUsers
特征将使用注册器(默认位于 app/Services/Registrar.php
)来验证和注册用户。
只要修改里面的create
方法就可以同时自动创建profile关系:
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;
}
关于php - 用户注册时自动创建个人资料(Laravel 5),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30608069/