簡體   English   中英

Laravel 上傳照片可選

[英]Laravel upload photo optional

    public function submitReview(Request $request){
        
        $request->validate([
            'comment'=> 'required',
            'R_Image' => 'mimes:kpg,png,jpeg|max:5048'


        ]);

        
            
        $newImageName = time() . '-' . $request->name . '.' . 
        $request->R_Image->extension();
        $request->R_Image->move(public_path('images'), $newImageName);
    


        $UserId=Auth::id();
        $query = DB::table('review') ->insert ([

                        'User_Id'=> $UserId,
                        'P_Id'=>$request->input('productID' ),
                        'R_Rating'=>$request->input('R_Rating' ),
                        'R_Comment'=>$request->input('comment' ),
                        'R_Image'=>$newImageName,
                        "created_at" =>  \Carbon\Carbon::now(), # new \Datetime()
                        "updated_at" => \Carbon\Carbon::now(), 
                    

                    ]);
        
        if ($query) {
            return back()-> with ('success' , 'Review has been successfully submitted');
        }else{
            return back() -> with ('fail' , 'Something went wrong');
        }

    }
}

這是我的審查代碼。 用戶可以在提交表單時上傳圖片,圖片不是必需的,這是可選的。 但是,當用戶不上傳圖像時,我收到錯誤消息“呼叫成員 function extension() on null”。 但是,如果提交帶有圖像的表單,我沒有收到錯誤。 我的代碼有問題嗎?

'R_Image' => 'mimes:`jpg`,png,jpeg|max:5048' 
public function submitReview(Request $request){
        
        $request->validate([
            'comment'=> 'required'
            ]);

        $newImageName = "";

        if ($request->hasFile('R_Image')) {
            $request->validate([
            'R_Image' => 'mimes:kpg,png,jpeg|max:5048'
            ]);

            $newImageName = time() . '-' . $request->name . '.' . 
            $request->R_Image->extension();
            $request->R_Image->move(public_path('images'), $newImageName);
        }

        $UserId=Auth::id();
        $query = DB::table('review') ->insert ([

                        'User_Id'=> $UserId,
                        'P_Id'=>$request->input('productID' ),
                        'R_Rating'=>$request->input('R_Rating' ),
                        'R_Comment'=>$request->input('comment' ),
                        'R_Image'=>$newImageName,
                        "created_at" =>  \Carbon\Carbon::now(), # new \Datetime()
                        "updated_at" => \Carbon\Carbon::now(), 
                    

                    ]);
        
        if ($query) {
            return back()-> with ('success' , 'Review has been successfully submitted');
        }else{
            return back() -> with ('fail' , 'Something went wrong');
        }

    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM