【发布时间】:2021-04-22 17:10:16
【问题描述】:
我想通过 Laravel 8 一次将多个图像上传到我的 SQL 数据库,但我无法做到。我只上传了一个,但是当我尝试更多时却失败了。
我的数据库
图像
| id | nombre | id_coche |
|---|---|---|
| 01 | name.jpg | 0004 |
| ... | ... | ... |
我的代码
形状之刃
@foreach ($Vehiculo as $obj) /*this is to take the Car ID*/
<form method="POST" action="{{ route('añadirImagen')}}" enctype="multipart/form-data" >
@csrf
<div class="form-row">
<div class="form-group col-md-3">
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">ID</span>
</div>
<input type="text" class="form-control" name="id_coche" value="{{$obj->id}}" style="background: white" required readonly>
</div>
</div>
<div class="col-md-6">
<input type="file" class="form-control" name="imagen" required multiple/>
</div>
<div class="form-group col-md-3">
<button type="submit" class="btn btn-success">AÑADIR IMAGENES</button>
</div>
</div>
</form>
@endforeach
控制器
“只上传一张图片”
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'nombre.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->file("imagen")!=null){
$nombre = $request->file('imagen');
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
$Imagenes->save();
return redirect()->back()->with('error','Se han añadido las imagenes correctamente.');
}
}
“我尝试上传多个”
public function añadirImagen(Request $request){
$validated = $request->validate([
'id_coche' => 'required',
'imagen.*' => 'mimes:image'
]);
$data = $request->input();
$id_coche = $data['id_coche'];
$Imagenes= new Imagenes;
$Imagenes->id_coche = $id_coche;
if($request->hasfile("imagen")){
$nombre_img = $request->file('imagen');
foreach($nombre_img as $nombre) {
$nombreFoto = $nombre->getClientOriginalName();
$nombre->move('img/Coches/', $nombreFoto);
$Imagenes->nombre = $nombreFoto;
}
}
$Imagenes->save();
执行此操作时,它会在数据库中添加一个具有正确 id_coche 的单行,Auto_Increment 可以很好地识别 ID,但名称仍然为 NULL。
谢谢。
【问题讨论】:
标签: php sql laravel image upload