18

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>
double-beep
  • 5,031
  • 17
  • 33
  • 41
Erasersharp
  • 360
  • 1
  • 3
  • 13

4 Answers4

32

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. Without it laravel would not understand the file.

like:

<form method="POST" enctype="multipart/form-data" name="formName">
double-beep
  • 5,031
  • 17
  • 33
  • 41
Jose Hernandez
  • 477
  • 4
  • 6
6

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();
}
Felix Eve
  • 3,811
  • 3
  • 40
  • 50
Naveen Kumar
  • 1,476
  • 5
  • 28
  • 52
4

you need add this code in your controller

if ($request->file('imgUpload1') == null) {
    $file = "";
}else{
   $file = $request->file('imgUpload1')->store('images');  
}
JeanMg25
  • 51
  • 3
1

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>
Terrymight
  • 69
  • 7