AppointmentDetail.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. <?php
  2. namespace App\Imports;
  3. use App\Components\AsyncResponse;
  4. use Illuminate\Support\Collection;
  5. use Illuminate\Support\Facades\Validator;
  6. use Maatwebsite\Excel\Concerns\ToCollection;
  7. use Maatwebsite\Excel\Concerns\WithHeadingRow;
  8. use Maatwebsite\Excel\Concerns\WithMultipleSheets;
  9. use Maatwebsite\Excel\Imports\HeadingRowFormatter;
  10. HeadingRowFormatter::default('none');
  11. class AppointmentDetail implements ToCollection,WithMultipleSheets,WithHeadingRow
  12. {
  13. use AsyncResponse;
  14. protected $row = ["条码","商品名称","数量"];
  15. public function sheets(): array
  16. {
  17. return [
  18. 0 => $this,
  19. ];
  20. }
  21. /**
  22. * @param Collection $collection
  23. */
  24. public function collection(Collection $collection)
  25. {
  26. $header = $collection->first();
  27. foreach ($this->row as $row)if (!isset($header[$row]))$this->error("表头不存在“".$row."”");
  28. $errors = Validator::make($collection->toArray(),[
  29. "*.条码" => ["required_without:*.商品名称"],
  30. "*.商品名称" => ["required_without:*.条码"],
  31. "*.数量" => ["required_without:*.条码","integer","min:1"],
  32. ],[
  33. 'required_without'=>':attribute 条码与商品名称,数量至少存在一组',
  34. 'integer'=>':attribute 必须为数字',
  35. 'min'=>':attribute 非法',
  36. ],[
  37. "*.条码" => "条码",
  38. "*.商品名称" => "商品名称",
  39. "*.数量" => "数量",
  40. ])->errors();
  41. if (count($errors)>0){
  42. $temp = [];
  43. foreach ($errors->toArray() as $key=>$arr){
  44. $key = explode(".",$key,2)[0];
  45. unset($collection[$key]);
  46. $key = $key+2;
  47. if (array_key_exists($key,$temp))$temp[$key] = array_merge($temp[$key],$arr);
  48. else $temp[$key] = $arr;
  49. }
  50. $errors = $temp;
  51. }
  52. $this->success(["data"=>$collection,"errors"=>$errors]);
  53. }
  54. }