Laravel调用null的extension()方法报错,BrandsController代码求助
错误排查:Call to a member function extension() on null
核心错误原因
- 字段名不统一:验证规则里用
image,但代码操作的是logo;更新分支里判断文件是否存在用的是photo,实际操作的是logo,导致文件检测失效,$post->logo为null时调用extension()触发报错。 - 验证规则拼写错误:
nimes是mimes的笔误,导致文件类型验证失效,且错误提示的logo字段和验证字段image不匹配。 - 新增分支未做文件存在判断:当用户未上传logo时,直接执行
$post->logo->extension(),此时$post->logo为null,触发报错。 - 模型调用错误:更新逻辑里用
Clients::find($brandsId),应该调用Brands模型,否则找不到对应数据实例。
解决方法及修正代码
1. 统一字段名&修正验证规则
将所有涉及文件的字段名统一为logo,修正mimes拼写错误,调整错误提示对应关系:
$messages = [ 'brand.required'=>'Brand not included', 'logo.mimes'=>'Invalid image format', 'logo.max'=>'Image size cannot exceed 2MB' ]; $post->validate([ 'brand'=>'required|unique:brands|max:20', 'logo'=>'nullable|mimes:jpg,jpeg,png,gif,svg|max:2048' ], $messages);
2. 新增分支添加文件存在判断
避免未传文件时调用extension():
}else{ $brands = new Brands(); if($post->hasFile('logo')){ $file = time().'.'.$post->logo->extension(); $post->logo->storeAs('public/uploads/images',$file); $brands->logo = 'storage/uploads/images/'.$file; } }
3. 修正模型调用&添加实例检测
更新逻辑里调用正确的Brands模型,同时检测实例是否存在,避免后续操作报错:
$brands = Brands::find($brandsId); if(!$brands){ return response()->json(['error'=>'Brand not found'], 404); } if($post->hasFile('logo')){ // 文件处理逻辑 }
完整修正代码
public function store(Request $post){ $messages = [ 'brand.required'=>'Brand not included', 'logo.mimes'=>'Invalid image format', 'logo.max'=>'Image size cannot exceed 2MB' ]; $post->validate([ 'brand'=>'required|unique:brands|max:20', 'logo'=>'nullable|mimes:jpg,jpeg,png,gif,svg|max:2048' ], $messages); $brandsId = $post->id; if($brandsId){ $brands = Brands::find($brandsId); if(!$brands){ return response()->json(['error'=>'Brand not found'], 404); } if($post->hasFile('logo')){ $file = time().'.'.$post->logo->extension(); $post->logo->storeAs('public/uploads/images',$file); $brands->logo = 'storage/uploads/images/'.$file; } }else{ $brands = new Brands(); if($post->hasFile('logo')){ $file = time().'.'.$post->logo->extension(); $post->logo->storeAs('public/uploads/images',$file); $brands->logo = 'storage/uploads/images/'.$file; } } $brands->brand = $post->brand; $brands->save(); return response()->json($brands); }
内容的提问来源于stack exchange,提问作者Nagi Aliyev
相关产品推荐
相关产品推荐

