[英]Laravel - Image Array Validation gives an Error to nullable validate
我只需要將圖像數組驗證為圖像和特定的圖像文件擴展名。 但是我對圖像的請求驗證允許我使用插入的可為空值
例如,我將添加內容,但不想添加圖像。 然后圖像應包含null,這就是為什么我需要將請求驗證為可為null的原因。 但是根據我的經驗,不允許使用null值,這會導致我出錯為什么? 請幫幫我
這是錯誤。
促銷圖片必須是圖片
這是我的控制器
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.');
}
這是我的觀點
{!! 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() !!}
無需在驗證中添加可為空的屬性。 像這樣更改您的驗證碼
$this->validate($request, [
'promotion_image.*' => 'image|max:1999'
]);
如果您需要用戶必須添加圖像輸入,則可以使用required
驗證規則,否則您就不需要這樣。
上面的代碼強制用戶添加圖像類型的文件或完全不添加任何文件。
希望您能理解,如果需要任何解釋,請隨時提出。
您需要將其驗證為數組:
$validator = Validator::make($request->all(), [
'photos.profile' => 'required|image',
]);
您有時可能希望將其結合使用,這表示當前驗證規則僅在存在該字段時才適用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.