简体   繁体   中英

Multiple images uploaded with Laravel

I have trying to make multiple images function with Laravel but I have received

'Invalid argument supplied for foreach()'

This is the function in the controller

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);
   }     

}

When I var_dump($files); it returns NULL .

The form is

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

My route:

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

make File true when you create your form

{!! Form::open(array('route' => 'image.upload', 'method' => 'POST', 'files' => true)) !!}

{!! 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() }}

Your Function

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();
        }
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM