Call to a member function store() on null - laravel 5.4

醉酒当歌 提交于 2019-12-12 16:17:52

问题


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.

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


回答1:


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.

like:

<form method="POST" enctype="multipart/form-data" name="formName">

Hope this solves your problem.




回答2:


The data is always fetched with name attribute which is missing in your form input

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



回答3:


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>



回答4:


you need add this code in your controller

if ($request->file('imgUpload1') == null) {
    $file = "";
}else{
   $file = $request->file('imgUpload1')->store('images');  
}


来源:https://stackoverflow.com/questions/42089208/call-to-a-member-function-store-on-null-laravel-5-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!