调用成员函数的details()是否为null?

时间:2019-05-29 17:12:22

标签: laravel laravel-5

我的代码是:

$user = User::create([
   'email' => $request->email,
    'password' => Hash::make($request->password),
 ]);

$user_details = [
            'name' => $request->name,
            'address' => $request->address,
            'lastname' => $request->lastname,
            'secondname' => $request->secondname,
            'inn' => $request->inn,
            'fincode' => $request->fincode,
        ];

$user->details()->create($user_details);

模型用户是:

class User extends Authenticatable implements JWTSubject
{
    use Notifiable;

    public function details()
    {
        return $this->hasOne(UserDetails::class, 'user_id', 'id');
    }

}

UserDetails 模型是:

namespace App;

use Illuminate\Database\Eloquent\Model;

class UserDetails extends Model
{

    protected $table = 'enterprise';

    protected $fillable = ['name', 'lastname', 'secondname', 'address', 'inn', 'fincode'];
}

1 个答案:

答案 0 :(得分:1)

我相信您的$user尚未保留,因此出现错误,在您的情况下,$user为null,这就是为什么您无法在details对象上调用null的原因。确保您在用户上使用了所有必填字段。

如果共享的内容是完整内容,则fillable模型中的User数组可能会丢失,然后添加以下内容:

protected $fillable = [ 'email', 'password'];