PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, January 4, 2022

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

 January 04, 2022     file-upload, laravel, laravel-5.3, php     No comments   

Issue

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 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"
]


Answered By - Paras
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing