Php Laravel-如果$request,则不更新照片->;文件(';photo';)为空
这里我有Laravel更新功能,因此使用该功能我更新字段,这里是重要的输入照片 我的代码是:Php Laravel-如果$request,则不更新照片->;文件(';photo';)为空,php,laravel,controller,request,insert-update,Php,Laravel,Controller,Request,Insert Update,这里我有Laravel更新功能,因此使用该功能我更新字段,这里是重要的输入照片 我的代码是: public function update($id, Requests\ArticleRequest $request) { $this->validate($request, [ 'photo' => 'image|max:10000', // validate also other fields here
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->file('photo')为空,那么我如何跳过照片…
如果(!$request->file('photo')
不足,但问题在于代码底部:$article_字段['photo']=$filename;所以这将更新我的照片列…如何跳过此操作?如果没有文件,您只需跳过更新该列即可。。
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');
}