AdminBaseController.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. <?php
  2. namespace App\Http\Controllers;
  3. use App\Http\Requests\Admin\CreateRequest;
  4. use App\Http\Requests\Admin\UpdateRequest;
  5. use App\Models\Config;
  6. use App\Servers\MenuServer;
  7. use Illuminate\Contracts\Routing\ResponseFactory;
  8. use Illuminate\Http\Request;
  9. use Illuminate\Support\Facades\DB;
  10. use Illuminate\Support\Facades\Schema;
  11. use Prettus\Repository\Criteria\RequestCriteria;
  12. use Prettus\Validator\Contracts\ValidatorInterface;
  13. use Prettus\Validator\Exceptions\ValidatorException;
  14. use function foo\func;
  15. class AdminBaseController extends Controller
  16. {
  17. const SUCCESS_MSG = '操作成功';
  18. const ERROR_MSG = '操作失败';
  19. protected $successMsg = "";
  20. protected $errorMsg = "";
  21. /**
  22. * @var null
  23. */
  24. protected $repository = null;
  25. /**
  26. * @var null
  27. */
  28. protected $validator = null;
  29. /**
  30. * @var null
  31. */
  32. protected $tables = null;
  33. /**
  34. * @var null
  35. */
  36. protected $modelCopy = null;
  37. /**
  38. * @var array
  39. *
  40. * 排除不需要被更新字段
  41. */
  42. protected $exceptUpdateField = ['id', 'created_at', 'updated_at'];
  43. /**
  44. * @var null Array
  45. *
  46. * 需要更新字段
  47. */
  48. protected $onlyUpdateField = null;
  49. /**
  50. * @var null
  51. */
  52. protected $indexWith = null;
  53. /**
  54. * @var null
  55. */
  56. protected $indexOrderBy = null;
  57. /**
  58. * @var bool
  59. *
  60. * 默认是否开启created_at字段DESC排序
  61. */
  62. protected $defaultCreatedAtDesc = true;
  63. public function __construct($repository, $validator)
  64. {
  65. $this->middleware('auth'); // 验证登录
  66. $this->repository = $repository;
  67. $this->validator = $validator;
  68. $this->modelCopy = $repository->makeModel(); // 重置model
  69. $this->tables = \Illuminate\Support\Str::camel($this->modelCopy->getTable()); // 获取指定表名称并转换成驼峰形式
  70. }
  71. // Admin response redirect
  72. protected function response($msg = self::SUCCESS_MSG, $status = 'success', $callback = '', $redirect = '', array $data = [])
  73. {
  74. $request = request();
  75. if ($status == 'success') {
  76. $this->successMsg ? $msg = $this->successMsg : null;
  77. } else {
  78. $this->errorMsg ? $msg = $this->errorMsg : null;
  79. }
  80. if ($request->wantsJson() || $request->ajax()) {
  81. if ($status == 'success' && empty($redirect)) {
  82. $redirect = '';
  83. }
  84. return response()->json([
  85. 'status' => $status,
  86. 'code' => $status == 'success'?1:0,
  87. 'message' => $msg,
  88. 'redirect' => $redirect,
  89. 'callback' => $callback,
  90. 'data' => $data
  91. ]);
  92. } else {
  93. return redirect()->back()->withErrors($msg)->withInput();
  94. }
  95. }
  96. /**
  97. * @param Request $request
  98. * @param ResponseFactory $response
  99. * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
  100. * @throws \Prettus\Repository\Exceptions\RepositoryException
  101. *
  102. */
  103. protected function index(Request $request, ResponseFactory $response)
  104. {
  105. if ($request->isMethod('post') && $request->ajax()) {
  106. // $this->repository->pushCriteria(app(RequestCriteria::class));
  107. // $query = $this->repository;
  108. //
  109. // if( !is_null($this->indexWith) || (is_array($this->indexWith) && !empty($this->indexWith)) ){
  110. // $query->with($this->indexWith);
  111. // }
  112. if (method_exists($this, "_indexJoin")) {
  113. $query = $this->_indexJoin();
  114. } else {
  115. $query = DB::table($this->modelCopy->getTable());
  116. }
  117. if (method_exists($this, "_indexSelect")) {
  118. $query->select($this->_indexSelect());
  119. }
  120. if (method_exists($this, "_indexScopeQuery")) {
  121. $query->where($this->_indexScopeQuery());
  122. }
  123. if (method_exists($this, "_indexOrderBy")) {
  124. $order_by = $this->_indexOrderBy();
  125. foreach ($order_by as $by_info) {
  126. $query->orderBy($by_info[0], $by_info[1]);
  127. }
  128. } elseif ($this->defaultCreatedAtDesc) {
  129. $query->orderBy('id', 'DESC');
  130. }
  131. if (!is_null($this->indexOrderBy) || (is_array($this->indexOrderBy) && !empty($this->indexOrderBy))) {
  132. foreach ($this->indexOrderBy as $key => $value) {
  133. $query->orderBy($key, $value);
  134. }
  135. }
  136. if(empty($request->pageSize))$request->pageSize=20;
  137. $datum = $query->paginate($request->pageSize);
  138. if (method_exists($this, "_indexPost")) {
  139. $datum = $this->_indexPost($datum);
  140. }
  141. if ($request->wantsJson()) {
  142. return $response->json([
  143. "total" => $datum->total(), // $datum->total() 返回总行数
  144. "rows" => $datum->items(), // 返回当前查询出来的数据
  145. "data" => $datum, // 返回当前对象
  146. ]);
  147. }
  148. }
  149. $params = array();
  150. if (method_exists($this, "_indexGet")) {
  151. $params = $this->_indexGet();
  152. }
  153. return view("admins.{$this->tables}.index", (array)$params);
  154. }
  155. /**
  156. * Store a newly created resource in storage.
  157. *
  158. * @param CreateRequest $request
  159. *
  160. * @return \Illuminate\Http\Response
  161. *
  162. * @throws \Prettus\Validator\Exceptions\ValidatorException
  163. */
  164. protected function store(CreateRequest $request)
  165. {
  166. try {
  167. if ($request->isMethod('post') && $request->ajax()) {
  168. $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_CREATE);
  169. if (method_exists($this, "_storePost")) {
  170. $page = $this->_storePost($request);
  171. } else {
  172. $page = $this->repository->create($request->all());
  173. }
  174. if ($page !== false) {
  175. return $this->response(self::SUCCESS_MSG, 'success', '', '');
  176. } else {
  177. return $this->response(self::ERROR_MSG, 'error');
  178. }
  179. }
  180. $params = [];
  181. if (method_exists($this, "_storeGet")) {
  182. $params = $this->_storeGet($request);
  183. }
  184. return response()->view("admins.{$this->tables}.create", (array)$params)->header('Content-Type', 'text/html');
  185. } catch (ValidatorException $e) {
  186. if ($request->wantsJson()) {
  187. $errors = $e->getMessageBag()->getMessages();
  188. $error = array_shift($errors);
  189. return response()->json([
  190. 'error' => true,
  191. 'message' => $error[0]
  192. ]);
  193. }
  194. return redirect()->back()->withErrors($e->getMessageBag())->withInput();
  195. }
  196. }
  197. /**
  198. * Show the form for editing the specified resource.
  199. *
  200. * @param int $id
  201. *
  202. * @return \Illuminate\Http\Response
  203. *
  204. */
  205. protected function edit($id = null)
  206. {
  207. if (method_exists($this, "_editGet")) {
  208. $params = $this->_editGet($id);
  209. } else {
  210. $params['model'] = $this->repository->find($id);
  211. }
  212. return view("admins.{$this->tables}.edit", (array)$params);
  213. }
  214. /**
  215. * Update the specified resource in storage.
  216. *
  217. * @param UpdateRequest $request
  218. * @param string $id
  219. *
  220. * @return Response
  221. *
  222. * @throws \Prettus\Validator\Exceptions\ValidatorException
  223. *
  224. */
  225. protected function update(UpdateRequest $request, $id = null)
  226. {
  227. try {
  228. if (method_exists($this, "_updatePost")) {
  229. $page = $this->_updatePost($request, $id);
  230. } else {
  231. $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_UPDATE);
  232. if (is_null($this->onlyUpdateField) || empty($this->onlyUpdateField) || !is_array($this->onlyUpdateField)) {
  233. $update = $request->except($this->exceptUpdateField);
  234. } else {
  235. $update = $request->only($this->onlyUpdateField);
  236. }
  237. $page = $this->repository->update($update, $id);
  238. }
  239. if ($page !== false) {
  240. return $this->response(self::SUCCESS_MSG, 'success', '', '');
  241. } else {
  242. return $this->response(self::ERROR_MSG, 'error');
  243. }
  244. } catch (ValidatorException $e) {
  245. if ($request->wantsJson()) {
  246. $errors = $e->getMessageBag()->getMessages();
  247. $error = array_shift($errors);
  248. return response()->json([
  249. 'error' => true,
  250. 'message' => $error[0]
  251. ]);
  252. }
  253. return redirect()->back()->withErrors($e->getMessageBag())->withInput();
  254. }
  255. }
  256. /**
  257. * 删除一行数据
  258. * @param Request $request
  259. * @param ResponseFactory $response
  260. * @param $id
  261. * @return \Illuminate\Http\JsonResponse
  262. */
  263. protected function destroy(Request $request, ResponseFactory $response, $id = null)
  264. {
  265. if ($request->isMethod('post') && $request->ajax()) {
  266. if (method_exists($this, "_destroy")) {
  267. $deleted = $this->_destroy($id);
  268. }else{
  269. $deleted = $this->repository->delete($id);
  270. }
  271. $deleted === false ? $data = [
  272. 'status' => 1,
  273. 'message' =>$this->errorMsg?: self::ERROR_MSG
  274. ] : $data = [
  275. 'status' => 0,
  276. 'message' => $this->successMsg?: self::SUCCESS_MSG
  277. ];
  278. if ($request->wantsJson()) {
  279. return $response->json($data);
  280. }
  281. }
  282. }
  283. /**
  284. * @param Request $request
  285. * @param ResponseFactory $response
  286. * @return \Illuminate\Http\JsonResponse
  287. * @throws \Exception
  288. *
  289. * 批量删除 banners 数据
  290. */
  291. protected function destroys(Request $request, ResponseFactory $response)
  292. {
  293. if ($request->isMethod('post') && $request->ajax()) {
  294. $ids = $request->params;
  295. $ids = explode(';', $ids);
  296. if (method_exists($this, "_destroys")) {
  297. $res = $this->_destroys($ids);
  298. }else{
  299. $res = $this->modelCopy->whereIn('id', $ids)->delete();
  300. }
  301. !$res ? $data = [
  302. 'status' => 1,
  303. 'message' => self::ERROR_MSG
  304. ] : $data = [
  305. 'status' => 0,
  306. 'message' => ''
  307. ];
  308. if ($request->wantsJson()) {
  309. return $response->json($data);
  310. }
  311. }
  312. }
  313. /**
  314. * 成功提示
  315. * @param $msg
  316. * @param string $url
  317. * @param string $data
  318. * @param string $code
  319. * @return string
  320. */
  321. protected function success($msg, $url = '', $data = '', $code = '1')
  322. {
  323. return json_encode(array('msg' => $msg, 'data' => $data, 'url' => $url, 'code' => $code,'status'=>$code*1));
  324. }
  325. /**
  326. * 错误提示
  327. * @param $msg
  328. * @param string $url
  329. * @param string $data
  330. * @param string $code
  331. * @return string
  332. */
  333. protected function error($msg, $url = '', $data = '', $code = '0')
  334. {
  335. return json_encode(array('msg' => $msg, 'data' => $data, 'url' => $url, 'code' => $code,'status'=>$code*1));
  336. }
  337. }