无法在Laravel 4中上传照片

时间:2014-07-27 12:29:26

标签: php forms file laravel laravel-4

我试图将一些产品添加到我的数据库中,我必须上传此产品的照片。我已经制作了一个控制器和视图,但是当我点击“创建”时,我没有任何错误,但我也没有照片。我想上传只有jpg,jpeg,gif,png文件我该怎么办?这是我的代码:

控制器:

public function postAddProduct(){
    $destinationPath = '';
    $filename        = '';
    $newId = Product::max('id')+1;
    $validator = Validator::make(Input::all(), array(
        'name' => 'required',       
        'description' => 'required',            
        'partner_link' => 'required',
        'image' => 'required'   
    ));
    if (Input::hasFile('image')) {
        $file            = Input::file('image');
        $destinationPath = public_path().'/uploads/products/';
        $filename        = $newId.'.'.$file->getClientOriginalExtension();
        $uploadSuccess   = $file->move($destinationPath, $filename);
    }

    if($validator->passes()){
        $product = new Product;
        $product->name = Input::get('name');
        $product->description = Input::get('description');
        $product->category_id = Input::get('category');
        $product->partner_link = Input::get('partner_link');
        $product->photo = $filename;
        $product->save();   

        return Redirect::back();
    }else{
        return Redirect::back()->withErrors($validator)->withInput();
    }

}

查看:

{{ Form::open(array('url'=>'user/admin/products/addd', 'class'=>'col-md-4', 'style'=> 'float:none; margin: 0 auto', 'id'=>'register-form')) }}
            <h2 class="form-signin-heading">Add Product</h2>    
            {{ Form::text('name', null, array('class'=>'form-control', 'placeholder'=>'Name')) }}    
            {{ Form::text('description', null, array('class'=>'form-control', 'placeholder'=>'Description')) }}
            {{ Form::text('partner_link', null, array('class'=>'form-control', 'placeholder'=>'Partner link')) }}
            {{Form::label('category', 'Category: ', array('class' => 'field-name'))}}
            <select name="category">
                <?php $i = 0; ?>
                @foreach($categories as $category)      
                    <optgroup label="{{$category['name']}}">
                    @foreach($category['subcategories'] as $sub)
                        <option value="{{$sub->id}}">{{$sub->name}}</option>
                    @endforeach
                    </optgroup>
                @endforeach
            </select>
            <div class="clearfix"></div>                
            {{Form::file('image', array('style' => 'margin-bottom: 10px'))}}
            {{ Form::submit('Save', array('class'=>'btn btn-large btn-primary btn-block'))}}
        {{ Form::close() }} 

1 个答案:

答案 0 :(得分:1)

您的表单应将'files'选项设置为'true':

{{ Form::open(array('url' => 'foo/bar', 'files' => true)) }}