我的更新用户管理表单中有错误,如果他有个人资料,我想更新与用户对应的个人资料。但它抛出了这个错误:
从空值创建默认对象
我在我的模型中设置了用户和配置文件Profile::where('id', $user->profile_id)->first();
之间的关系,但是当我dd
它总是为空时,即使有相应的配置文件。
user.php的
public function profile()
{
return $this->hasOne('App\Profile', 'user_id', 'id');
}
Profile.php
public function user()
{
return $this->belongsTo('App\User');
}
功能错误在
public function update(Request $request, User $user)
{
if(\Auth::check()) {
if(\Auth::user()->type == 'admin') {
$validated = $request->validate([
'name' => 'required',
'email' => 'required|email',
'password' => 'confirmed'
]);
if(!empty($validated['password'])){
if(!$user->profile){
//Has no profile
$user->name = $validated['name'];
$user->email = $validated['email'];
$user->password = bcrypt($validated['password']);
$user->update();
} else {
//Has profile
$profile = Profile::where('id', $user->profile_id)->first();
$profile->username = $validated['name'];
$profile->email = $validated['email'];
$profile->update();
$user->name = $validated['name'];
$user->email = $validated['email'];
$user->password = bcrypt($validated['password']);
$user->update();
}
} else {
if(!$user->profile){
//Has no profile
$user->name = $validated['name'];
$user->email = $validated['email'];
$user->update();
} else {
//Has profile
$profile = Profile::where('id', $user->profile_id)->first();
$profile->username = $validated['name'];
$profile->email = $validated['email'];
$profile->update();
$user->name = $validated['name'];
$user->email = $validated['email'];
$user->update();
}
}
}
}
}
在这些线上$profile = Profile::where('id', $user->profile_id)->first();
由于您在user_id
表中使用profiles
作为外键,因此您可以将此视为您的声明:
Profile :: where('user_id',$ user-> id) - > first();
或者,通过使用以下关系:
$用户>概况;
您可以使用您的关系并将逻辑压缩为:
$user->name = $validated['name'];
$user->email = $validated['email'];
if(!empty($validated['password'])){
$user->password = bcrypt($validated['password']);
$profile = $user->profile;
$profile->username = $validated['name'];
$profile->email = $validated['email'];
$profile->save();
}
$user->save();