foreach statement causes undefined variable fileNameToStore in multiple file upload

  laravel, php, sql, visual-studio-code

Im trying to upload more than a single file so I try to modify the code a little bit. But everytime I’m adding foreach($request->file(‘image’) as $file). I always get an error about having undefined variable. I attached my controller code below, Any idea how can I fix this and make the multiple file upload?

        foreach($request->file('image') as $file)
        $filenameWithExt =$request->file('image')->getClientOriginalName();
        $filename = pathinfo($filenameWithExt, PATHINFO_FILENAME);
        $extension = $request->file('image')->getClientOriginalExtension();
        $fileNameToStore = $filename. '_'.time().'.'.$extension;
        $path = $request->file('image')->storeAs('public/images', $fileNameToStore);
    $post = new Post;
    $post->cover_image = $fileNameToStore;
    return redirect('/dashboard')->with('success', 'Post Created!');

Source: Laravel

Leave a Reply