Laravel-图像阵列验证为可为空的验证提供了一个错误

时间:2018-11-25 14:02:44

标签: php mysql arrays laravel laravel-5

我只需要将图像阵列验证为图像和特定的图像文件扩展名。但是我对图像的请求验证允许我使用插入式可空值

例如,我将添加内容,但不想添加图像。然后图像应包含null,这就是为什么我需要将请求验证为可为null的原因。但是根据我的经验,不允许使用null值,这会导致我出错为什么?请帮助我

这是错误。

  

促销图片必须是图片

这是我的 CONTROLLER

 public function store(Request $request)
    {
        $this->validate($request, [
            'promotion_image' => 'image|nullable|max:1999'
        ]);

            $promotion = [];

        if ($request->has('promotion_image'))
        {   
            //Handle File Upload

            foreach ($request->file('promotion_image') as $key => $file)
            {
                // Get FileName
                $filenameWithExt = $file->getClientOriginalName();
                //Get just filename
                $filename = pathinfo( $filenameWithExt, PATHINFO_FILENAME);
                //Get just extension
                $extension = $file->getClientOriginalExtension();
                //Filename to Store
                $fileNameToStore = $filename.'_'.time().'.'.$extension;
                //Upload Image
                $path = $file->storeAs('public/promotion_images',$fileNameToStore);
                array_push($promotion, $fileNameToStore);
            }

            $fileNameToStore = serialize($promotion);
        }
        else
        {
            $fileNameToStore='noimage.jpg';
        }

        if (count($promotion)) {
            $implodedPromotion = implode(' , ', $promotion);
            $promotionImage = new Promotion;
            $promotionImage->promotion_image = $implodedPromotion;
            $promotionImage->save();

            return redirect('/admin/airlineplus/promotions')->with('success', 'Image Inserted');
        }

        return redirect('/admin/airlineplus/promotions')->with('error', 'Something went wrong.');


        }

这是我的 VIEW

    {!! Form::open(['action'=>'Admin\PromotionsController@store', 'method' => 'POST','enctype'=>'multipart/form-data', 'name' => 'add_name', 'id' => 'add_name']) !!}
<div class="form-group">   
    <div class="table-responsive">  
        <table class="table table-bordered" id="dynamic_field">  
           <tr>  
              <td> {{ Form::file('promotion_image[]')}}</td>

              <td>{{ Form::button('', ['class' => 'btn btn-success fa fa-plus-circle', 'id'=>'add','name'=>'add', 'style'=>'font-size:15px;']) }}</td>
           </tr>  
        </table>  
        {{Form::submit('submit', ['class'=>'btn btn-primary', 'name'=>'submit'])}}
    </div> 
</div>  
{!! Form::close() !!}

2 个答案:

答案 0 :(得分:1)

无需在验证中添加可为空的属性。只需像这样更改您的验证码

$this->validate($request, [
        'promotion_image.*' => 'image|max:1999'
    ]);

如果您需要用户必须添加图像输入,则可以使用required验证规则,否则您就不需要这样。

以上代码强制用户添加图像类型的文件或完全不添加任何文件。

希望您能理解,如果需要任何解释,请随时提问。

答案 1 :(得分:0)

您需要将其验证为数组:

$validator = Validator::make($request->all(), [
    'photos.profile' => 'required|image',
]);

看看laravel docs

您有时可能希望将其与结合使用,这表明当前的验证规则仅在存在该字段时才适用。

相关问题