Laravel 5.7在控制器中循环时为foreach()提供了无效的参数

时间:2019-05-20 10:42:45

标签: php laravel file

当我尝试在控制器内执行循环时,出现错误Invalid argument supplied for foreach(),我无法真正弄清原因。我有一个form,应该可以上传多个文件

这是我到目前为止所得到的:

use App\SingleApplication;
use App\SingleApplicationFile;

$application = SingleApplication::create([
   'email' => request()->email,
   'name' => request()->name,
    ...// more fields
]);

$allowedfileExtension = ['pdf', 'jpg', 'png', 'docx'];
$files = request()->has('attachment');
if ($files) {
     foreach ($files as $file) {
       $filename = $file->getClientOriginalName();
       $extension = $file->getClientOriginalExtension();
       $filesize = $file->getSize();
       $check = in_array($extension, $allowedfileExtension);

       if ($check) {

         foreach ($file as $att) {
         $filename = Storage::disk('local')->put('attachments', request()->file($att));
          SingleApplicationFile::create([
             'files_id' => $application->id,
             'single_application_id' => $application->id,
             'attachment' => $filename,
             'attachment_name' => $extension,
             'attachment_size' => $filesize,
          ]);
        }
     }
  }
}

那么,我在这里做什么错了?

1 个答案:

答案 0 :(得分:3)

这是一个布尔值

$files = request()->hasFile('attachment'); // return  if has file not array of files

您应该将文件另存为

$files = request()->file('attachment'); // returns array of files

或者您可以将条件更改为

$hasfiles = request()->hasFile('attachment');

if ($hasfiles) {

    $files = request()->file('attachment');
    // your rest code
  

注意:文件检查应使用hasFile进行,因为file和其他   字段是不同的。

这里是参考文献link