从空值laravel 5.7创建默认对象

时间:2019-02-27 16:19:14

标签: php laravel laravel-5.7

我的更新用户管理表单中有一个错误,如果他有个人资料,我想更新与该用户对应的个人资料。但这会引发此错误:

  

从空值创建默认对象

我在模型中设置了用户和个人资料Profile::where('id', $user->profile_id)->first();之间的关系,但是当我dd时,即使有相应的个人资料,它始终为null。

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();

2 个答案:

答案 0 :(得分:0)

由于您正在使用user_id作为profiles表中的外键,因此您可以将其作为语句:

Profile :: where('user_id',$ user-> id)-> first();

或者,通过使用以下关系:

$ user->个人资料;

答案 1 :(得分:0)

您可以使用关系,也可以将逻辑压缩为:

@echo off
setlocal EnableDelayedExpansion

set ips[0]=192.168.0.1
set 192.168.0.1=router
set ips[1]=192.168.0.2
set 192.168.0.2=printer
set ips[2]=192.168.0.3
set 192.168.0.3=nas