[英]Laravel 5.2 How I Can Update Form in Condition The Files Forms is Blank?
Hy again. again I'm trying to updated my form, with multiple upload.
我正在尝试更新我的表单,并进行多次上传。 It's work.
是工作。 But, whenever I tried to blank the files form, it's always appear:
但是,每当我尝试清空文件表单时,它总是出现:
ErrorException in ProductController.php line 160: Undefined offset: 0
ProductController.php 160行中的ErrorException:未定义的偏移量:0
Okay, now I have two(or three) options: 好的,现在我有两个(或三个)选项:
Here's my code (work well, unless if I'm not fill the files form): 这是我的代码(效果很好,除非我不填写文件表格):
public function update(Request $request, $id)
{
$update = $request->all();
//dd($update);
$product = Product::find($id);
$picture = '';
$images = [];
if ($request->hasFile('images')) {
$files = $request->file('images');
//dd($files);
foreach($files as $file){
if (isset($file)){
$filename = $file->getClientOriginalName();
$extension = $file->getClientOriginalExtension();
$picture = date('His').$filename;
$destinationPath = base_path() . '\public\images/';
$file->move($destinationPath, $picture);
array_push($images, $picture);
}
}
//dd($update);
//dd($images);
}
if (!empty($update['images']) && isset($images)) {
$update['images'] = $images[0];
$update['images2'] = $images[1];
$update['images3'] = $images[2];
$update['images4'] = $images[3];
} else {
unset($product['images'] -> $images);
}
//dd($update);
$product->update($update);
return redirect('product');
}
And the form: 以及形式:
<div class="form-group">
{!! Form::label('Images', 'Images:') !!}
{!! Form::file('images[]',null,['class'=>'form-control']) !!}
</div>
Thank you, have a nice day! 感谢您有一个愉快的一天!
The issue here is that when your images
array is empty you can't access the [0]
index. 这里的问题是,当您的
images
数组为空时,您将无法访问[0]
索引。 However, this is compounded by the fact that your conditional is always true. 但是,您的条件始终为真这一事实使情况更加复杂。 The conditional statement you've used is insufficient here:
您在这里使用的条件语句不足:
isset($images);
This is because previously you declared
images. 这是因为以前您
declared
图像。
$images = [];
So instead what you want is to check the count
of the images array. 因此,您想要的是检查images数组的
count
。 We can do that like this: 我们可以这样做:
count($images) > 0
So the final conditional would be: 因此,最终条件将是:
if (!empty($update['images']) && count($images) > 0) {
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.