在Laravel我正在尝试更新图像并且它可以工作,但是当我决定不添加新文件时,我收到此错误:一般错误:1364 [重复]
This question already has an answer here:
I'm trying to update a table and it works perfectly but when I try to update whiteout changing the file it fails and gives me this error.
The error:
SQLSTATE[HY000]: General error: 1364 Field 'poster' doesn't have a default value (SQL: insert into patrocinadores
(nombre
, link
, categoria
, updated_at
, created_at
) values (Patrocinadores, http://127.0.0.1:8000/patrocinadores/creates, 3, 2017-05-01 23:44:44, 2017-05-01 23:44:44))
Here is my controller store()
public function store(Request $request){
$this->validate(request(), [
'nombre' => 'required',
'link' => 'required',
'poster' => 'image|image_size:<=1000',
'categoria' =>'required',
]);
$patrocinadores = new Patrocinadores;
$patrocinadores->nombre = request('nombre');
$patrocinadores->link = request('link');
$newFoto=request()->file('poster');
if($newFoto){
$name=$newFoto. '.' . $newFoto->getClientOriginalExtension();
$patrocinadores->poster = $newFoto->move('./uploads/', $name);
}
$patrocinadores->categoria = request('categoria');
$patrocinadores->save();
return redirect('/patrocinadores'); }
HTML:
<div class="form-control-file">
<label for="poster">Póster</label>
<input type="file" class="form-control-file" id="poster" name="poster" aria-describedby="fileHelp" accept="image/*" >
<br>
<div id="preview"><img src="{{asset($patrocinadores->poster)}}" ></div>
</div>
</div>
The only place you set the poster field is in the if statement... so if $request->file() returns null it will never get set... probably what happens...
$newFoto=request()->file('poster');
if($newFoto){
$name=$newFoto. '.' . $newFoto->getClientOriginalExtension();
$patrocinadores->poster = $newFoto->move('./uploads/', $name);
}
Now $newFoto is an instance of Illuminate\Http\UploadedFile, the move() method on it returns a file object...
You could take advantage of the storeAs() method and store the path of the file in the database... like so:
$patrocinadores->poster = $request->poster->storeAs('uploads', $name);
Note that this will store it in your storage directory under uploads (/storage/uploads) which I prefer over root... now even better... you can check for file upload success, the user could abort on you...
if ($request->file('poster')->isValid()) {
$patrocinadores->poster = $request->poster->storeAs('uploads', $name);
}
else{
$patrocinadores->poster = 'path to default photo or avatar';
}
Hope this helps...