使用Laravel上传的多张图片

时间:2016-11-01 09:24:21

标签: php mysql image laravel-4

我试图让多个图像与Laravel一起运行,但我收到了

  

'为foreach()'

提供的参数无效

这是控制器中的功能

public function uploadSubmit() {

$files = Input::file('image');
$file_count = count($files);
$gallery = 0;

    foreach($files as $file) {

        $gallery = new Gallery;    
        $rules = array('file' => 'required');
        $validator = Validator::make(array('file'=> $file), $rules);

        if($validator->passes()){

        $filename = str_random(20);
        $file->move(public_path() . '/uploads', $filename . '.' . $file->getClientOriginalExtension());
        $imagePath = '/uploads/' . $filename . '.' . $file->getClientOriginalExtension();

        $image = Image::make(public_path() . $imagePath);

            $image->save();
    $gallery ++;
        $gallery->image = $imagePath;
        $gallery->save();
        }
   }
   if($gallery == $file_count){
        return Redirect::to('/admin/upload')->with('message', 'image added.');
   } 
   else 
   {
        return Redirect::to('/admin/upload')->withInput()->withErrors($validator);
   }     

}

当我var_dump($files);时,它会返回NULL

表单是

{{ Form::open() }}
    {{ Form::file('image[]', array('multiple'=>true)) }}
        <hr />
        <button type="submit" class="btn btn-primary">upload</button>           
{{ Form::close() }}

我的路线:

Route::get ('/admin/upload', ['uses' => 'AdminController@upload', 'before' => 'admin']);
Route::post('/admin/upload', ['uses' => 'AdminController@uploadSubmit', 'before' => 'csrf|admin']);

1 个答案:

答案 0 :(得分:2)

创建表单时

使文件成立

  

{!! Form :: open(array('route'=&gt;'image.upload','method'=&gt;'POST',   'files'=&gt;真))!!}

{!! Form::open(array('route' => 'image.upload', 'method' => 'POST',   'files' => true)) !!}
    {{ Form::file('image[]', array('multiple'=>true)) }}
        <hr />
        <button type="submit" class="btn btn-primary">upload</button>           
{{ Form::close() }}

你的功能

public function uploadSubmit() {
    $files = Input::file('image');
    $file_count = count($files);
    foreach($files as $file) {
        $gallery = new Gallery;    
        $rules = array('file' => 'required');
        $validator = Validator::make(array('file'=> $file), $rules);
        if($validator->passes()){
            $filename = str_random(20). '.' . $file->getClientOriginalExtension();
            $file->move('uploads', $filename );
        $gallery->image = $filename;
        $gallery->save();
        }
   }
}
相关问题