[英]upload image as optional in laravel 8
我想使用 laravel 8 上傳圖片,我使用以下代碼:
$post = new Post;
$upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
$req->image_name->move('uploads', $upload_image_name);
$post->title = $req->input('title');
$post->image_name = $upload_image_name;
$post->save();
它工作正常,但是當圖像為空時,我Call to a member function getClientOriginalName() on null
出錯。
這是因為,令人驚訝的是,圖像是空的,而圖像是空的
添加條件以檢查上傳的圖像
$post = new Post;
$post->title = $req->input('title');
if($req->image_name)
$upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
$req->image_name->move('uploads', $upload_image_name);
$post->image_name = $upload_image_name;
}
$post->save();
如果需要圖像 - 在開始時添加驗證 - 但正確的方法 - 在表單請求中進行驗證
$request->validate([
'image_name' => 'required|image',
'title' => 'required|string'
]);
如果不需要圖像 - 更改遷移並使 posts.image_name 可為空
我使用以下代碼,但我認為這不是傳統方式。 這是代碼:
if($req->hasFile('image_name')){
$upload_image_name = time().'_'.$req->image_name->getClientOriginalName();
$req->image_name->move('uploads', $upload_image_name);
}
else
$upload_image_name = "Noimage";
$post = new Post;
$post->title = $req->input('title');
$post->image_name = $upload_image_name;
$post->save();
因為我使用了我的上一個 Laravel 項目。
$image = $request->file('thumbnail');
if (isset($image)) {
$imageName = date('y_m_d') . "_" . uniqid().".".$image->getClientOriginalExtension();
if (!Storage::disk('public')->exists('thumbnail')) {
Storage::disk('public')->makeDirectory('thumbnail');
}
$postImage = Image::make($image)->stream();
Storage::disk('public')->put('thumbnail/' . $imageName, $postImage);
} else {
$imageName = "";
}
$post = new Post;
$post->title = $request->title;
$post->image_name = $imageName;
$post->save();
image_name 列應該可以為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.