123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384 |
- <?php
- namespace App\Http\Controllers;
- use App\Http\Requests\Admin\CreateRequest;
- use App\Http\Requests\Admin\UpdateRequest;
- use App\Models\Config;
- use App\Servers\MenuServer;
- use Illuminate\Contracts\Routing\ResponseFactory;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Schema;
- use Prettus\Repository\Criteria\RequestCriteria;
- use Prettus\Validator\Contracts\ValidatorInterface;
- use Prettus\Validator\Exceptions\ValidatorException;
- use function foo\func;
- class AdminBaseController extends Controller
- {
- const SUCCESS_MSG = '操作成功';
- const ERROR_MSG = '操作失败';
- protected $successMsg = "";
- protected $errorMsg = "";
- /**
- * @var null
- */
- protected $repository = null;
- /**
- * @var null
- */
- protected $validator = null;
- /**
- * @var null
- */
- protected $tables = null;
- /**
- * @var null
- */
- protected $modelCopy = null;
- /**
- * @var array
- *
- * 排除不需要被更新字段
- */
- protected $exceptUpdateField = ['id', 'created_at', 'updated_at'];
- /**
- * @var null Array
- *
- * 需要更新字段
- */
- protected $onlyUpdateField = null;
- /**
- * @var null
- */
- protected $indexWith = null;
- /**
- * @var null
- */
- protected $indexOrderBy = null;
- /**
- * @var bool
- *
- * 默认是否开启created_at字段DESC排序
- */
- protected $defaultCreatedAtDesc = true;
- public function __construct($repository, $validator)
- {
- $this->middleware('auth'); // 验证登录
- $this->repository = $repository;
- $this->validator = $validator;
- $this->modelCopy = $repository->makeModel(); // 重置model
- $this->tables = \Illuminate\Support\Str::camel($this->modelCopy->getTable()); // 获取指定表名称并转换成驼峰形式
- }
- // Admin response redirect
- protected function response($msg = self::SUCCESS_MSG, $status = 'success', $callback = '', $redirect = '', array $data = [])
- {
- $request = request();
- if ($status == 'success') {
- $this->successMsg ? $msg = $this->successMsg : null;
- } else {
- $this->errorMsg ? $msg = $this->errorMsg : null;
- }
- if ($request->wantsJson() || $request->ajax()) {
- if ($status == 'success' && empty($redirect)) {
- $redirect = '';
- }
- return response()->json([
- 'status' => $status,
- 'code' => $status == 'success'?1:0,
- 'message' => $msg,
- 'redirect' => $redirect,
- 'callback' => $callback,
- 'data' => $data
- ]);
- } else {
- return redirect()->back()->withErrors($msg)->withInput();
- }
- }
- /**
- * @param Request $request
- * @param ResponseFactory $response
- * @return \Illuminate\Contracts\View\Factory|\Illuminate\Http\JsonResponse|\Illuminate\View\View
- * @throws \Prettus\Repository\Exceptions\RepositoryException
- *
- */
- protected function index(Request $request, ResponseFactory $response)
- {
- if ($request->isMethod('post') && $request->ajax()) {
- // $this->repository->pushCriteria(app(RequestCriteria::class));
- // $query = $this->repository;
- //
- // if( !is_null($this->indexWith) || (is_array($this->indexWith) && !empty($this->indexWith)) ){
- // $query->with($this->indexWith);
- // }
- if (method_exists($this, "_indexJoin")) {
- $query = $this->_indexJoin();
- } else {
- $query = DB::table($this->modelCopy->getTable());
- }
- if (method_exists($this, "_indexSelect")) {
- $query->select($this->_indexSelect());
- }
- if (method_exists($this, "_indexScopeQuery")) {
- $query->where($this->_indexScopeQuery());
- }
- if (method_exists($this, "_indexOrderBy")) {
- $order_by = $this->_indexOrderBy();
- foreach ($order_by as $by_info) {
- $query->orderBy($by_info[0], $by_info[1]);
- }
- } elseif ($this->defaultCreatedAtDesc) {
- $query->orderBy('id', 'DESC');
- }
- if (!is_null($this->indexOrderBy) || (is_array($this->indexOrderBy) && !empty($this->indexOrderBy))) {
- foreach ($this->indexOrderBy as $key => $value) {
- $query->orderBy($key, $value);
- }
- }
- if(empty($request->pageSize))$request->pageSize=20;
- $datum = $query->paginate($request->pageSize);
- if (method_exists($this, "_indexPost")) {
- $datum = $this->_indexPost($datum);
- }
- if ($request->wantsJson()) {
- return $response->json([
- "total" => $datum->total(), // $datum->total() 返回总行数
- "rows" => $datum->items(), // 返回当前查询出来的数据
- "data" => $datum, // 返回当前对象
- ]);
- }
- }
- $params = array();
- if (method_exists($this, "_indexGet")) {
- $params = $this->_indexGet();
- }
- return view("admins.{$this->tables}.index", (array)$params);
- }
- /**
- * Store a newly created resource in storage.
- *
- * @param CreateRequest $request
- *
- * @return \Illuminate\Http\Response
- *
- * @throws \Prettus\Validator\Exceptions\ValidatorException
- */
- protected function store(CreateRequest $request)
- {
- try {
- if ($request->isMethod('post') && $request->ajax()) {
- $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_CREATE);
- if (method_exists($this, "_storePost")) {
- $page = $this->_storePost($request);
- } else {
- $page = $this->repository->create($request->all());
- }
- if ($page !== false) {
- return $this->response(self::SUCCESS_MSG, 'success', '', '');
- } else {
- return $this->response(self::ERROR_MSG, 'error');
- }
- }
- $params = [];
- if (method_exists($this, "_storeGet")) {
- $params = $this->_storeGet($request);
- }
- return response()->view("admins.{$this->tables}.create", (array)$params)->header('Content-Type', 'text/html');
- } catch (ValidatorException $e) {
- if ($request->wantsJson()) {
- $errors = $e->getMessageBag()->getMessages();
- $error = array_shift($errors);
- return response()->json([
- 'error' => true,
- 'message' => $error[0]
- ]);
- }
- return redirect()->back()->withErrors($e->getMessageBag())->withInput();
- }
- }
- /**
- * Show the form for editing the specified resource.
- *
- * @param int $id
- *
- * @return \Illuminate\Http\Response
- *
- */
- protected function edit($id = null)
- {
- if (method_exists($this, "_editGet")) {
- $params = $this->_editGet($id);
- } else {
- $params['model'] = $this->repository->find($id);
- }
- return view("admins.{$this->tables}.edit", (array)$params);
- }
- /**
- * Update the specified resource in storage.
- *
- * @param UpdateRequest $request
- * @param string $id
- *
- * @return Response
- *
- * @throws \Prettus\Validator\Exceptions\ValidatorException
- *
- */
- protected function update(UpdateRequest $request, $id = null)
- {
- try {
- if (method_exists($this, "_updatePost")) {
- $page = $this->_updatePost($request, $id);
- } else {
- $this->validator->with($request->all())->passesOrFail(ValidatorInterface::RULE_UPDATE);
- if (is_null($this->onlyUpdateField) || empty($this->onlyUpdateField) || !is_array($this->onlyUpdateField)) {
- $update = $request->except($this->exceptUpdateField);
- } else {
- $update = $request->only($this->onlyUpdateField);
- }
- $page = $this->repository->update($update, $id);
- }
- if ($page !== false) {
- return $this->response(self::SUCCESS_MSG, 'success', '', '');
- } else {
- return $this->response(self::ERROR_MSG, 'error');
- }
- } catch (ValidatorException $e) {
- if ($request->wantsJson()) {
- $errors = $e->getMessageBag()->getMessages();
- $error = array_shift($errors);
- return response()->json([
- 'error' => true,
- 'message' => $error[0]
- ]);
- }
- return redirect()->back()->withErrors($e->getMessageBag())->withInput();
- }
- }
- /**
- * 删除一行数据
- * @param Request $request
- * @param ResponseFactory $response
- * @param $id
- * @return \Illuminate\Http\JsonResponse
- */
- protected function destroy(Request $request, ResponseFactory $response, $id = null)
- {
- if ($request->isMethod('post') && $request->ajax()) {
- if (method_exists($this, "_destroy")) {
- $deleted = $this->_destroy($id);
- }else{
- $deleted = $this->repository->delete($id);
- }
- $deleted === false ? $data = [
- 'status' => 1,
- 'message' =>$this->errorMsg?: self::ERROR_MSG
- ] : $data = [
- 'status' => 0,
- 'message' => $this->successMsg?: self::SUCCESS_MSG
- ];
- if ($request->wantsJson()) {
- return $response->json($data);
- }
- }
- }
- /**
- * @param Request $request
- * @param ResponseFactory $response
- * @return \Illuminate\Http\JsonResponse
- * @throws \Exception
- *
- * 批量删除 banners 数据
- */
- protected function destroys(Request $request, ResponseFactory $response)
- {
- if ($request->isMethod('post') && $request->ajax()) {
- $ids = $request->params;
- $ids = explode(';', $ids);
- if (method_exists($this, "_destroys")) {
- $res = $this->_destroys($ids);
- }else{
- $res = $this->modelCopy->whereIn('id', $ids)->delete();
- }
- !$res ? $data = [
- 'status' => 1,
- 'message' => self::ERROR_MSG
- ] : $data = [
- 'status' => 0,
- 'message' => ''
- ];
- if ($request->wantsJson()) {
- return $response->json($data);
- }
- }
- }
- /**
- * 成功提示
- * @param $msg
- * @param string $url
- * @param string $data
- * @param string $code
- * @return string
- */
- protected function success($msg, $url = '', $data = '', $code = '1')
- {
- return json_encode(array('msg' => $msg, 'data' => $data, 'url' => $url, 'code' => $code,'status'=>$code*1));
- }
- /**
- * 错误提示
- * @param $msg
- * @param string $url
- * @param string $data
- * @param string $code
- * @return string
- */
- protected function error($msg, $url = '', $data = '', $code = '0')
- {
- return json_encode(array('msg' => $msg, 'data' => $data, 'url' => $url, 'code' => $code,'status'=>$code*1));
- }
- }
|