14
votes

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>
4
<input type="file" id="imgUpload1"> has no name attributeAdam
Well... that's stupid on my behalf. Thanks!Erasersharp
Not stupid it happens, fresh eyes are all that was needed :)Adam
inside your input tag replace id with name like this <input type="file" name="imgUpload1">Azlan Jamal

4 Answers

24
votes

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">
5
votes

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

you need add this code in your controller

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

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>