98 lines
2.7 KiB
PHP
98 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers\Goods;
|
|
|
|
use App\Http\Controllers\Controller;
|
|
use App\Http\Resources\GoodsBrandResource;
|
|
use App\Models\GoodsBrand;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Validator;
|
|
use Illuminate\Validation\Rule;
|
|
|
|
class GoodsBrandsController extends Controller
|
|
{
|
|
public function index()
|
|
{
|
|
$goodsBrands = GoodsBrand::query()->paginate();
|
|
|
|
return GoodsBrandResource::collection($goodsBrands);
|
|
}
|
|
|
|
public function store(Request $request)
|
|
{
|
|
$validator = Validator::make($request->all(), [
|
|
'names' => 'required|array',
|
|
'names.*' => 'required|string|max:255|unique:goods_brands,name',
|
|
]);
|
|
if ($validator->fails()) {
|
|
$this->res = [
|
|
'httpCode' => 400,
|
|
'errorCode' => 400416,
|
|
'errorMessage' => $validator->getMessageBag()->getMessages(),
|
|
];
|
|
goto end;
|
|
}
|
|
$goodsBrands = [];
|
|
foreach ($request->names as $name) {
|
|
$goodsBrands[] = ['name' => $name];
|
|
}
|
|
$goodsBrand = new GoodsBrand();
|
|
if (!$goodsBrand->batchInsert($goodsBrands)) {
|
|
$this->res = [
|
|
'httpCode' => 500,
|
|
'errorCode' => 500500,
|
|
'errorMessage' => '批量添加失败',
|
|
];
|
|
}
|
|
end:
|
|
|
|
return response($this->res, $this->res['httpCode']);
|
|
}
|
|
|
|
public function show($id)
|
|
{
|
|
return new GoodsBrandResource(GoodsBrand::query()->find($id));
|
|
}
|
|
|
|
public function update($id, Request $request)
|
|
{
|
|
$validator = Validator::make($request->all(), [
|
|
'name' => [
|
|
'required',
|
|
'string',
|
|
'max:255',
|
|
Rule::unique('goods_brands')->ignore($id),
|
|
]
|
|
]);
|
|
if ($validator->fails()) {
|
|
$this->res = [
|
|
'httpCode' => 400,
|
|
'errorCode' => 400416,
|
|
'errorMessage' => $validator->getMessageBag()->getMessages(),
|
|
];
|
|
return response($this->res, $this->res['httpCode']);
|
|
}
|
|
$goodsBrand = GoodsBrand::query()->find($id);
|
|
$goodsBrand->name = request('name');
|
|
$goodsBrand->save();
|
|
|
|
return new GoodsBrandResource($goodsBrand);
|
|
}
|
|
|
|
public function destroy($id)
|
|
{
|
|
$goodsBrand = GoodsBrand::query()->find($id);
|
|
try {
|
|
$goodsBrand->delete();
|
|
} catch (\Exception $e) {
|
|
$this->res = [
|
|
'httpCode' => 500,
|
|
'errorCode' => 500416,
|
|
'errorMessage' => $e->getMessage(),
|
|
];
|
|
}
|
|
|
|
return response($this->res, $this->res['httpCode']);
|
|
}
|
|
}
|