Search code examples
phplaravellaravel-5file-upload

Laravel : $request->hasFile() is not working


I have a form where I get the title, description, and an image. When I dd($requests->all());, It returns the following which is correct.

array:4 [
  "projectTitle" => "asd"
  "project_description" => "asd"
  "project_image" => "15940723_1336567063030425_9215184436331587115_n.jpg"
  "_token" => "eUj27iioySvIgut5Afu0ZHMgeVrO99a9e1o7Tw0w"
]

And I am storing the values as :

$project = new Portfolio;
$project->freelancer_id = Auth::user()->id;
$project->title = $request->get('projectTitle');
$project->description = $request->get('project_description');

if($request->hasFile('project_image')){
   $project_image = $request->file('project_image');
   $filename = time() . '.' . $project_image->getClientOriginalExtension();
   Image::make($project_image)->resize(197, 137)->save( public_path('/uploads/portfolios/' . $filename ) );
   $project->img = $filename;
}

$project->save();

But the img DB table field gets null.

The if($request->hasFile('project_image')) is not getting the field,

Also, I have a form where the method is POST and have enctype="multipart/form-data" and a for file I have <input type="file" name="project_image" id="project_image">.

What have I done wrong?


Solution

  • The error is not in your backend code. Looks like it's an error in your frontend code.

    As you can see the output of dd($request->all()) returned

    array:4 [
      "projectTitle" => "asd"
      "project_description" => "asd"
      "project_image" => "15940723_1336567063030425_9215184436331587115_n.jpg"
      "_token" => "eUj27iioySvIgut5Afu0ZHMgeVrO99a9e1o7Tw0w"
    ]
    

    Your project_image is just a string whereas it should have been an UploadedFile object/instance like so:

    array:4 [
      "projectTitle" => "asd"
      "project_description" => "asd"
      "project_file" => UploadedFile {#30 
        -test: false
        -originalName: "15940723_1336567063030425_9215184436331587115_n.jpg"
        -mimeType: "image/jpeg"
        -size: 5126
        -error: 0
      }
      "_token" => "eUj27iioySvIgut5Afu0ZHMgeVrO99a9e1o7Tw0w"
    ]