68 lines
1.7 KiB
PHP
68 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\Producto;
|
|
use Illuminate\Http\JsonResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Http\Response;
|
|
use Illuminate\Validation\Rule;
|
|
|
|
class ProductController extends Controller
|
|
{
|
|
public function index(): JsonResponse
|
|
{
|
|
return response()->json(Producto::query()->latest()->get());
|
|
}
|
|
|
|
public function store(Request $request): JsonResponse
|
|
{
|
|
$validated = $request->validate($this->rules());
|
|
|
|
$producto = Producto::create($validated);
|
|
|
|
return response()->json($producto, 201);
|
|
}
|
|
|
|
public function show(Producto $producto): JsonResponse
|
|
{
|
|
return response()->json($producto);
|
|
}
|
|
|
|
public function update(Request $request, Producto $producto): JsonResponse
|
|
{
|
|
$validated = $request->validate($this->rules($producto->id));
|
|
|
|
$producto->update($validated);
|
|
|
|
return response()->json($producto);
|
|
}
|
|
|
|
public function destroy(Producto $producto): Response
|
|
{
|
|
$producto->delete();
|
|
|
|
return response()->noContent();
|
|
}
|
|
|
|
/**
|
|
* @return array<string, mixed>
|
|
*/
|
|
protected function rules(?int $productoId = null): array
|
|
{
|
|
return [
|
|
'tenant_codigo' => ['required', 'string', 'exists:tenants,codigo'],
|
|
'categoria_id' => ['required', 'integer'],
|
|
'slug' => [
|
|
'required',
|
|
'string',
|
|
'max:255',
|
|
Rule::unique('productos', 'slug')->ignore($productoId),
|
|
],
|
|
'nombre' => ['required', 'string', 'max:255'],
|
|
'descripcion' => ['nullable', 'string'],
|
|
'precio' => ['required', 'numeric', 'min:0'],
|
|
];
|
|
}
|
|
}
|