Livewire中Call to a member function store() on null错误解决求助
解决Livewire中
Call to a member function store() on null错误 问题根源
当未上传graduation_certificate文件时,$this->graduation_certificate的值为null,直接调用store()方法会触发该错误。
解决方法
在创建UserTrainee记录时,先判断文件是否存在,仅当文件存在时才执行store()方法,否则传入null。以下是两种实现方式:
方式一:提前处理文件路径(可读性更强)
修改Livewire组件的submit方法:
public function submit() { $user_uni = User::create([ 'name' => "{$this->firstName} {$this->lastName}", 'type_id' => $this->userType, 'email' => $this->email, 'password' => bcrypt($this->password), 'gender' => $this->gender, 'mobile' => $this->mobile, 'is_active' => 1, ]); // 单独处理可空的毕业证明文件 $graduationCertPath = null; if ($this->graduation_certificate) { $graduationCertPath = $this->graduation_certificate->store('files', 'public'); } UserTrainee::create([ 'user_id' => $user_uni->id, 'region_id' => $this->region, 'city_id' => $this->city, 'university_id' => $this->university, 'department_id' => $this->department, 'major' => $this->major, 'student_number' => $this->studentNumber, 'gpa' => $this->gpa, 'gpa_type' => $this->gpa_type, 'training_date' => $this->training_date, 'training_hours' => $this->trainingHours, 'graduation_year' => $this->graduation_year, 'academic_degree' => $this->academic_degree, 'graduation_certificate' => $graduationCertPath, 'academic_transaction' => $this->academic_transaction->store('files', 'public'), 'cv' => $this->cv->store('files', 'public'), 'is_graduate' => $this->traineeType, ]); }
方式二:使用三元运算符(代码更简洁)
直接在create数组中处理:
public function submit() { $user_uni = User::create([ 'name' => "{$this->firstName} {$this->lastName}", 'type_id' => $this->userType, 'email' => $this->email, 'password' => bcrypt($this->password), 'gender' => $this->gender, 'mobile' => $this->mobile, 'is_active' => 1, ]); UserTrainee::create([ 'user_id' => $user_uni->id, 'region_id' => $this->region, 'city_id' => $this->city, 'university_id' => $this->university, 'department_id' => $this->department, 'major' => $this->major, 'student_number' => $this->studentNumber, 'gpa' => $this->gpa, 'gpa_type' => $this->gpa_type, 'training_date' => $this->training_date, 'training_hours' => $this->trainingHours, 'graduation_year' => $this->graduation_year, 'academic_degree' => $this->academic_degree, 'graduation_certificate' => $this->graduation_certificate ? $this->graduation_certificate->store('files', 'public') : null, 'academic_transaction' => $this->academic_transaction->store('files', 'public'), 'cv' => $this->cv->store('files', 'public'), 'is_graduate' => $this->traineeType, ]); }
额外注意
确保Livewire组件中已声明对应属性:
public $graduation_certificate;
内容的提问来源于stack exchange,提问作者Bshayer
相关产品推荐
相关产品推荐

