Skip to content
Advertisement

$request->hasFile() returns false when uploading

I can’t seem to get my app to upload a file when submitting a request in my Laravel 5.8 application. No matter what type of file I upload, hasFile() always returns false.

Form

<form action="{{ route('items.store') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <div class="form-group py-50">
        <input type="file" name="featured_img" value="featured_img" id="featured_img">
    </div>                    
      
    <div class="form-group">    
        <input type="submit" class="btn btn-primary" value="Upload Image" name="submit">
    </div>                                    
</form>

Controller

/**
 * Store a newly created resource in storage.
 *
 * @param  IlluminateHttpRequest  $request
 * @return IlluminateHttpResponse
 */
public function store(Request $request)
{
    //Check if image has been uploaded
    if($request->hasFile('featured_img')){
        return "True!"; 
    } else {
        return "False!";
    }  
}

dd() Output

array:7 [▼
  "_token" => "sREFSO8bs0rWil05AESVrwEl37XtKOJAF2nCkTNR"
  "status" => "published"
  "featured_img" => "example.jpg"
  "submit" => "Upload Image"
]
  • enctype="multipart/form-data" has been included in my form.
  • I have tested multiple files which are around 50-80 KB in size
  • I am running another Laravel app in the same environment without any issues. I also tested uploading the same images to that app without any problems. This leads me to believe this has nothing to do with misconfiguration of php.ini
  • dd($request->all()); returns a string name for "featured_img" instead of file object

UPDATE

While Making changes to my view I did not realize I had two form actions in place with the same route. Stupid me. Thank you for everyone that helped me troubleshoot.

Advertisement

Answer

I tested in one of my installation with in web.php

use IlluminateHttpRequest;
Route::get('test', function(){
    return view('test');
});
Route::post('test', function(Request $request){
    dd($request->hasFile('test'));
})->name('test');

in test.blade.php

<form action="{{ route('test') }}" method="POST" enctype="multipart/form-data">
    @csrf
   <div class="form-group py-50">
     <input type="file" name="test" id="featured_img">
   </div>                    

    <div class="form-group">    
      <input type="submit" class="btn btn-primary" value="Upload Image" name="submit">
    </div>

  </form>

$request->hasFile('test') returns true, please check with this code in your controller or route file and let me know, if you are getting any issue.

Also

You should use @stack to add script to your blade and not @section

Update

According to your updated view page code, you have two form in your view posting to same route check that and first form is not closed and second is open.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement