113 lines
3.1 KiB
PHP
113 lines
3.1 KiB
PHP
<?php
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Brand;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Validator;
|
|
|
|
class BrandController extends Controller
|
|
{
|
|
public function index(Request $request)
|
|
{
|
|
$validator = Validator::make($request->all(), [
|
|
'page' => 'integer|min:1',
|
|
'limit' => 'integer|min:1|max:100',
|
|
'name' => 'string|nullable',
|
|
]);
|
|
|
|
if ($validator->fails()) {
|
|
return $this->error(422, '参数错误', $validator->errors());
|
|
}
|
|
|
|
$query = Brand::query();
|
|
if ($request->filled('name')) {
|
|
$query->where('name', 'like', "%{$request->name}%");
|
|
}
|
|
|
|
$list = $query->paginate($request->input('limit', 10));
|
|
return $this->success([
|
|
'list' => $list->items(),
|
|
'total' => $list->total(),
|
|
'current_page' => $list->currentPage(),
|
|
'last_page' => $list->lastPage(),
|
|
]);
|
|
}
|
|
|
|
public function show($id)
|
|
{
|
|
$brand = Brand::find($id);
|
|
if (!$brand) {
|
|
return $this->error(404, '品牌不存在');
|
|
}
|
|
return $this->success($brand);
|
|
}
|
|
|
|
public function store(Request $request)
|
|
{
|
|
$validator = Validator::make($request->all(), [
|
|
'code' => 'required|string|unique:brands,code',
|
|
'name' => 'required|string|max:255',
|
|
'remark' => 'nullable|string',
|
|
]);
|
|
|
|
if ($validator->fails()) {
|
|
return $this->error(422, '参数错误', $validator->errors());
|
|
}
|
|
|
|
$brand = Brand::create($request->all());
|
|
return $this->success($brand, '创建成功', 201);
|
|
}
|
|
|
|
public function update(Request $request, $id)
|
|
{
|
|
$brand = Brand::find($id);
|
|
if (!$brand) {
|
|
return $this->error(404, '品牌不存在');
|
|
}
|
|
|
|
$validator = Validator::make($request->all(), [
|
|
'code' => 'sometimes|string|unique:brands,code,' . $id,
|
|
'name' => 'sometimes|string|max:255',
|
|
'remark' => 'nullable|string',
|
|
]);
|
|
|
|
if ($validator->fails()) {
|
|
return $this->error(422, '参数错误', $validator->errors());
|
|
}
|
|
|
|
$brand->update($request->all());
|
|
return $this->success($brand, '更新成功');
|
|
}
|
|
|
|
public function destroy($id)
|
|
{
|
|
$brand = Brand::find($id);
|
|
if (!$brand) {
|
|
return $this->error(404, '品牌不存在');
|
|
}
|
|
$brand->delete();
|
|
return $this->success(null, '删除成功');
|
|
}
|
|
|
|
public function all()
|
|
{
|
|
$list = Brand::select('id', 'name', 'code')->get();
|
|
return $this->success($list);
|
|
}
|
|
|
|
private function success($data = null, $message = 'success', $code = 200)
|
|
{
|
|
return response()->json([
|
|
'code' => $code,
|
|
'data' => $data,
|
|
'message' => $message
|
|
], $code);
|
|
}
|
|
|
|
private function error($code, $message, $errors = null)
|
|
{
|
|
$response = ['code' => $code, 'message' => $message];
|
|
if ($errors) $response['errors'] = $errors;
|
|
return response()->json($response, $code);
|
|
}
|
|
} |