【发布时间】:2017-06-12 18:29:12
【问题描述】:
我想为用户添加另一个详细信息,我所做的是在我的注册中创建了一个额外的字段,所以它是这样的:
<h1>Other Details</h1>
<div class="form-group{{ $errors->has('phone') ? ' has-error' : '' }}">
<input id="phone" type="text" class="form-control" name="phone" placeholder="phone number" />
@if ($errors->has('phone'))
<span class="help-block">
<strong>{{ $errors->first('phone') }}</strong>
</span>
@endif
</div>
<div class="form-group{{ $errors->has('address') ? ' has-error' : '' }}">
<textarea name="address" id="address" placeholder="your address" class="form-control"></textarea>
@if ($errors->has('address'))
<span class="help-block">
<strong>{{ $errors->first('address') }}</strong>
</span>
@endif
</div>
然后在 RegisterController 中,我在验证中添加了这些字段:
protected function validator(array $data)
{
return Validator::make($data, [
'lastname' => 'required|max:255',
'firstname' => 'required|max:255',
'username' => 'required|max:16|unique:users',
'email' => 'required|email|max:255|unique:users',
'password' => 'required|min:6|confirmed',
'phone' => 'required',
'address' => 'required'
]);
}
然后在验证部分我没有问题,但在保存到表时我不知道如何获取插入的用户 ID。
我为这样的配置文件创建了迁移:
public function up()
{
Schema::create('user_profile', function (Blueprint $table) {
$table->increments('id');
$table->unsignedInteger('user_id');
$table->string('phone');
$table->text('address');
$table->timestamps();
$table->foreign('user_id')
->references('id')
->on('users')
->onDelete('cascade');
});
}
然后我还为用户配置文件创建了一个模型
class UserProfile extends Model
{
protected $table = 'user_profile';
public function user() {
return $this->belongsTo('App\User');
}
}
然后在我的用户模型中我也添加了关系:
class User extends Authenticatable
{
use 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',
];
public function profile() {
return $this->hasOne('App\UserProfile');
}
}
那么我的问题是保存配置文件。因为在 RegisterController 我只有这个:
protected function create(array $data)
{
return User::create([
'name' => title_case($data['lastname']) . ' ' . title_case($data['firstname']),
'username' => $data['username'],
'email' => $data['email'],
'password' => bcrypt($data['password']),
]);
}
如何添加我的其他详细信息?我还是 Laravel 的新手。
【问题讨论】:
标签: php laravel laravel-5.3