我认为,different attribute such as pic_1,pic_2,pic_3 为你的cars 单表让你处理文件很麻烦。我的建议是,使用relationship。如果是这样,您将一些关于汽车的信息存储到您的cars 表中。每辆车可能有多个图像作为汽车证据显示。在这种情况下,最好创建另一个表,例如car_evidence,在此表中创建两个名为cars_id 和car_images 的列。然后建立他们之间的关系。如果您这样做,那么您可以根据需要动态提交更多汽车图像。 pic_1,pic_2,pic_3 属性不是更好的方法。请看一下我的过程-
你的 Cars.php 模型 -
class Cars extends Model
{
protected $primaryKey = 'cars_id';
protected $fillable = [
//your cars table's other fields
];
public function carevidence()
{
return $this->hasMany('App\CarEvidence', 'cars_id', 'id');
}
}
通过运行php artisan make:model CarEvidence -m 迁移创建一个新模型CarEvidence。然后,在这个迁移文件中,像这样添加两个columns -
$table->bigInteger('cars_id')->unsigned()->nullable();
$table->string('car_images');
你的 CarEvidence.php 模型应该看起来像 -
class CarEvidence extends Model
{
protected $fillable = [
'cars_id', 'car_images',
];
public function car(){
return $this->belongsTo('App\Cars', 'cars_id', 'id');
}
}
形式是-
<form action="your-route-or-url-here" method="post" enctype="multipart/form-data">
@csrf
//your other input fields about car information here, I think if any
<input type="file" name="carEvidence[]" multiple>
<button type="submit">Save</button>
</form>
Web.php
Route::post('/your-form-action-url-here', 'YourControllerHere@YourMethodHere');
然后在你的控制器方法中-
public function YourMethodHere(Request $request){
$this->validate($request, [
'carEvidence.*' => 'required|mimes:jpeg,png,jpg,gif,svg|max:2048',
]);
$post = new Cars;
//$post->carEvidence = "yes";here other information about car to save in `cars` table
if ($post->save()) {
if($request->hasFile('carEvidence')){
$files = $request->file('carEvidence');
foreach($files as $file){
$extension = $file->getClientOriginalExtension();
$filename =time().'.'.$extension;
$file->move(public_path('/image'), $filename);
CarEvidence::create([
'cars_id' => $post->id,
'car_images' => $filename
]);
}
}
}
return redirect('/internalaudit')->with('success', "Has been sent for Validation");
}
最后,在返回刀片文件期间
public function yourmethodname()
{
$cars = Cars::with('carevidence')->get();
return view('your-view-blade-file', compact('cars'));
}
然后在your-view-blade-file 中获取汽车图像(证据),您可以使用嵌套的foreach 循环-
@if (session('success'))
<div class="alert alert-success">{{ session('success') }}</div>
@endif
@if ($errors->any())
<div class="alert alert-danger">
<ul>
@foreach ($errors->all() as $error)
<li>{{ $error }}</li>
@endforeach
</ul>
</div>
@endif
@foreach($cars as $car)
<p>{{ $car->your-fields-from-cars-table }}</p>
//and get all relevant images for car by this
@foreach($car->carevidence as $evidence)
<img src="{{ asset('image/'.$evidence->car_images) }}" height="60px" width="60px" />
@endforeach
@endforeach
希望对你有帮助!