Skip to content
Advertisement

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

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

array:10 [▼
  "_token" => "HAf1f0m6kH54atYXUSb0UMpXcNdmA3IR46iTwt83"
  "title" => null
  "imagePost" => IlluminateHttpUploadedFile {#259 ▼
    -test: false
    -originalName: "07_ducati_diavel_base.jpg"
    -mimeType: "image/jpeg"
    -error: 0
  }
]

Here is my code for image processing:

public function create(Request $request)
    {
        // dd($request->all());
        $imagePost = 'IMAGE-POST'.time().$request->file('imagePost')->getClientOriginalName();
        
        if($request->hasFile('imagePost'))
        {
            // ec
            $filee = $request->image;
            $fileName = $filee->getClientOriginalName();
            $filee->move('uploads/posts',$fileName);
            $image = $fileName;
        }
        $status = $request->input('status');
        DB::table('post')->insert([
            'image'=> $image
        ]);
    }

But the img DB table field gets null.

The if($request->hasFile('imagePost')) is not getting the field.

What have i done wrong?

Advertisement

Answer

You are modifying file object before you check it with hasFile() condition. first check if $request has file then modify it according to your use “

public function create(Request $request)
{
    // dd($request->all());        
    
    if($request->hasFile('imagePost'))
    {
        $imagePost = 'IMAGE-POST'.time().$request->file('imagePost')->getClientOriginalName();
        // ec
        $filee = $request->image;
        $fileName = $filee->getClientOriginalName();
        $filee->move('uploads/posts',$fileName);
        $image = $fileName;
    }
    $status = $request->input('status');
    DB::table('post')->insert([
        'image'=> $image
    ]);
}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement