这里我有Laravel更新功能,所以使用此功能我更新字段,这里有重要的输入 PHOTO
我的代码是:
public function update($id, Requests\ArticleRequest $request)
{
$this->validate($request, [
'photo' => 'image|max:10000',
// validate also other fields here
]);
// checking file is valid.
if (!$request->file('photo')->isValid()) return redirect()->back()->withErrors(["photo" => "File is corrupt"]);
// file is valid
$destinationPath = public_path().'/images'; // upload path
$extension = $request->file('photo')->getClientOriginalExtension(); // getting image extension
$filename = str_random(5).'.'.$extension; // give a name to the image
$request->file('photo')->move($destinationPath, $filename); // uploading file to given path
// sending back with message
$article = Auth::user()->articles()->findOrFail($id); //if article id is unique just write Article::findOrFail($id)
$article_fields = $request->except('photo');
$article_fields['photo'] = $filename;
$article->update($article_fields);
Alert::message('Your auction is updated', 'Wonderful!');
return redirect('auctions');
}
所以当我选择一些图片来更新照片时,一切都很好,但是当我想更新其他文件和照片以保持相同的数据库时......我收到错误:
Call to a member function isValid() on a non-object
如果$ request->文件('照片')为空,我如何跳过照片,因此不会选择新图片...
答案 0 :(得分:0)
public function update($id, Requests\ArticleRequest $request){
**//check if file provided**
if ($request->hasFile('photo')) {
$this->validate($request, [
'photo' => 'image|max:10000',
// validate also other fields here
]);
// checking file is valid.
if (!$request->file('photo')->isValid()) return redirect()->back()->withErrors(["photo" => "File is corrupt"]);
// file is valid
$destinationPath = public_path().'/images'; // upload path
$extension = $request->file('photo')->getClientOriginalExtension(); // getting image extension
$filename = str_random(5).'.'.$extension; // give a name to the image
$request->file('photo')->move($destinationPath, $filename); // uploading file to given path
// sending back with message
$article = Auth::user()->articles()->findOrFail($id); //if article id is unique just write Article::findOrFail($id)
$article_fields = $request->except('photo');
$article_fields['photo'] = $filename;
$article->update($article_fields);
Alert::message('Your auction is updated', 'Wonderful!');
return redirect('auctions');
}
Alert::message('Nothing to update', 'So sad!');
return redirect('auctions');
}