UnitController.php 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Components\AsyncResponse;
  4. use App\Services\common\BatchUpdateService;
  5. use App\Unit;
  6. use Illuminate\Http\Request;
  7. use Illuminate\Support\Facades\Gate;
  8. use Illuminate\Support\Facades\Validator;
  9. class UnitController extends Controller
  10. {
  11. use AsyncResponse;
  12. public function index()
  13. {
  14. if(!Gate::allows('计量单位-查询')){ return redirect(url('/')); }
  15. $units=Unit::query()->orderBy("sequence")->paginate(50);
  16. return view('maintenance.unit.index',['units'=>$units]);
  17. }
  18. public function destroy($id)
  19. {
  20. if(!Gate::allows('计量单位-删除')){ return redirect(url('/')); }
  21. Unit::destroy($id);
  22. return ['success'=>true];
  23. }
  24. public function save()
  25. {
  26. $this->gate("计量单位-录入");
  27. $errors = $this->validatorUnit(request(),request("id"))->errors();
  28. if (count($errors)>0)$this->success(["errors"=>$errors]);
  29. $obj = ["name"=>request("name"),"sequence"=>request("sequence") ?? 0];
  30. if (request("id")){
  31. Unit::query()->where("id",request("id"))->update($obj);
  32. $this->success();
  33. }
  34. $this->success(Unit::query()->create($obj));
  35. }
  36. public function sort()
  37. {
  38. $this->gate("计量单位-录入");
  39. if (request("update") && count(request("update"))>1)app(BatchUpdateService::class)->batchUpdate("units",request("update"));
  40. $this->success();
  41. }
  42. protected function validatorUnit(Request $request,$id){
  43. if ($id){$name=$id;}
  44. $validator=Validator::make($request->input(),[
  45. 'name'=>['required','max:10',isset($name)?"unique:units,name,$name":'unique:units,name'],
  46. ],[
  47. 'required'=>':attribute 为必填项',
  48. 'max'=>':attribute 过长',
  49. 'unique'=>':attribute 已存在',
  50. ],[
  51. 'name'=>'计量单位名称',
  52. ]);
  53. return $validator;
  54. }
  55. public function getUnits()
  56. {
  57. return ["success"=>true,"data"=>app("UnitService")->getSelection()];
  58. }
  59. }