diff --git a/app/Admin/Controllers/AdminController.php b/app/Admin/Controllers/AdminController.php index f4e10aa..cdfb37a 100644 --- a/app/Admin/Controllers/AdminController.php +++ b/app/Admin/Controllers/AdminController.php @@ -4,13 +4,38 @@ namespace App\Admin\Controllers; use Illuminate\Http\Request; use Illuminate\Support\Arr; +use Illuminate\Validation\ValidationException; use Slowlyo\OwlAdmin\Controllers\AdminController as Controller; +use Symfony\Component\HttpKernel\Exception\HttpExceptionInterface; +use Throwable; /** * @property \App\Admin\Services\BaseService $service */ abstract class AdminController extends Controller { + public function update(Request $request) + { + $input = $request->all(); + + if ($this->actionOfQuickEditItem()) { + Arr::pull($input, $this->service->primaryKey()); + + if ($request->filled('_editable')) { + $input = Arr::only($input, explode(',', $request->input('_editable'))); + } + } + + try { + $result = $this->service->update($this->getPrimaryValue($request), $input); + } catch (Throwable $th) { + return $this->renderExceptionResponse( + tap($th, fn () => report($th)) + ); + } + return $this->autoResponse($result, __('admin.save')); + } + public function getQuickEditItemPath(array $editable = ['*']) { $params = ['_action' => 'quickEditItem']; @@ -22,20 +47,16 @@ abstract class AdminController extends Controller return $this->getUpdatePath().'?'.http_build_query($params); } - public function update(Request $request) + protected function renderExceptionResponse(Throwable $e) { - $data = $request->all(); + $message = 'Server error'; - if ($this->actionOfQuickEditItem()) { - Arr::pull($data, $this->service->primaryKey()); - - if ($request->filled('_editable')) { - $data = Arr::only($data, explode(',', $request->input('_editable'))); - } + if ($e instanceof ValidationException) { + $message = $e->validator->errors()->first(); + } elseif ($e instanceof HttpExceptionInterface) { + $message = $e->getMessage(); } - $result = $this->service->update($this->getPrimaryValue($request), $data); - - return $this->autoResponse($result, __('admin.save')); + return $this->response()->fail($message); } }