Laravel - Request Validation to Image set as Nullable is not



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

例如,我将添加一个内容,而不想添加图像。那么图像应该包含null,这就是为什么我需要将请求验证为null。但根据我的经验,空值是不允许的,这给了我错误,为什么?请帮帮我

这是错误。

未定义变量:促销

这是我的控制器

public function store(Request $request)
{
$this->validate($request, [
'promotion_image' => 'image|nullable|max:1999'
]);
if ($request->has('promotion_image'))
{   
//Handle File Upload
$promotion = [];
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'=>'AdminPromotionsController@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() !!}

您需要在if ($request->has('promotion_image'))之上声明$promotion = [],而不是在其内部。

因此:

public function store(Request $request)
{
$this->validate($request, [
'promotion_image' => 'image|nullable|max:1999'
]);
$promotion = [];
if ($request->has('promotion_image'))
{   
//Handle File Upload

这是因为您在表单中选择了图像以外的文件。请参阅以下内容以限制用户只能上传图像。

<input accept=".png, .jpg, jpeg" name="files[]" type="file" multiple>

不确定,但尝试一次

'promotion_image' => 'nullable|mimes:jpeg,jpg,png,gif|max:1999'

最新更新