2017-09-27 65 views
9

控制器功能:如何驗證在laravel中插入的圖像數組,並需要根據驗證插入枚舉值?

public function addImages(Request $request,$imagesProductId) 
{ 
    $product = Product::create($request->all()); 
    $filenames = array(); 

    if ($request->images == '') { 
     return Redirect::back()->withErrors(['msg', 'The Message']); 
    } 

    if() { 
    // also need to validate on the extension and resolution of images 
    // (ie., if the validation fails the enum value will be "QCFailed") 
    } else { 
     foreach ($request->images as $photo) { 
      $filename = substr($photo->store('public/uploadedImages'), 22); 
      $filenames[] = asset('storage/uploadedImages/'.$filename); 

      ProductsPhoto::create([ 
       'product_id' => $product->id, 
       'productId'  => $imagesProductId, 
       'nonliveStatus' =>"QCVerified", 
       'filename'  => $filename 
      ]); 
     } 

     // echo('nonliveStatus'); 
    } 

    return response()->json($filenames); 
} 

這是myfunction的插入images.For的陣列,我已經使用兩個圖像model.The陣列獲得插入,但基於該枚舉值應分別插入驗證..我的驗證是圖像是必需的,最大尺寸及其擴展

+0

任何人??? ...... –

回答

2

根據Laravel 5.4 documentation您需要創建具有規則集的驗證器對象。像這樣的東西:

public function addImages(Request $request, $imagesProductId) 
{ 
    $product = Product::create($request->all()); 
    $filenames = array(); 

    if (empty($request->images)) { 
     return Redirect::back()->withErrors(['msg', 'The Message']); 
    } 

    $rules = [ 
     'images' => 'mimes:jpeg,jpg,png'     // allowed MIMEs 
      . '|max:1000'        // max size in Kb 
      . '|dimensions:min_width=100,min_height=200' // size in pixels 
    ]; 

    $validator = Validator::make($request->all(), $rules); 
    $result = $validator->fails() ? 'QCFailed' : 'QCVerified'; 

    foreach ($request->images as $photo) { 
     $filename = substr($photo->store('public/uploadedImages'), 22); 
     $filenames[] = asset('storage/uploadedImages/'.$filename); 

     ProductsPhoto::create([ 
      'product_id' => $product->id, 
      'productId'  => $imagesProductId, 
      'nonliveStatus' => $result, 
      'filename'  => $filename 
     ]); 
    } 

    return response()->json($filenames); 
}