在 null 上调用成员函数 store() - laravel 5.4
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42089208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Call to a member function store() on null - laravel 5.4
提问by Erasersharp
I'm trying to upload an image though everytime I submit it's returning that the store() on null error. I've set the form to enctype="multipart/form-data" which hasn't helped.
我正在尝试上传图像,但每次提交时都会返回 store() 为 null 错误。我已将表单设置为 enctype="multipart/form-data" 这并没有帮助。
Can anyone point me in the right direction?
任何人都可以指出我正确的方向吗?
Thanks.
谢谢。
Function inside the controller
控制器内部功能
public function store(Request $request){
$file = $request->file('imgUpload1')->store('images');
return back();
}
Form below:
表格如下:
<form action="/imgupload" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="imgUpload1">File input</label>
<input type="file" id="imgUpload1">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
solved: was missing name tag on input field
已解决:输入字段上缺少名称标签
回答by Jose Hernandez
I had the same issue what I did to fix is in the opening form tag add enctype="multipart/form-data"that should fix it. With out it laravel would not understand the file.
我遇到了同样的问题,我要修复的是在打开表单标签中添加enctype="multipart/form-data"应该修复它。如果没有它,laravel 将无法理解该文件。
like:
喜欢:
<form method="POST" enctype="multipart/form-data" name="formName">
Hope this solves your problem.
希望这能解决您的问题。
回答by Naveen Kumar
The data is always fetched with name attribute which is missing in your form input
始终使用表单输入中缺少的 name 属性获取数据
Change
改变
<input type="file" id="imgUpload1">
to
到
<input type="file" id="imgUpload1" name = "imgUpload1">
and do some validation in the controller side like this
并像这样在控制器端做一些验证
$val = Validator:make($request->all, [
'imgUpload1' => 'required',
]);
if($val->fails()) {
return redirect()->back()->with(['message' => 'No file received']);
}
else {
$file = $request->file('imgUpload1')->store('images');
return redirect()->back();
}
回答by Terrymight
you are getting error because your store function is not seeing the file from your request from the input tag so to fix this set the "name" just I have done below
您收到错误,因为您的商店功能没有看到来自输入标签的请求中的文件,因此要修复此设置“名称”,我刚刚在下面完成了
<form action="/imgupload" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="form-group">
<label for="imgUpload1">File input</label>
<input type="file" id="imgUpload1" name="imgUpload1">
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
回答by JeanMg25
you need add this code in your controller
您需要在控制器中添加此代码
if ($request->file('imgUpload1') == null) {
$file = "";
}else{
$file = $request->file('imgUpload1')->store('images');
}