Add ProductController and Producto model with CRUD operations and migration
This commit is contained in:
67
app/Http/Controllers/ProductController.php
Normal file
67
app/Http/Controllers/ProductController.php
Normal file
@@ -0,0 +1,67 @@
|
||||
<?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_id' => ['required', 'integer'],
|
||||
'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'],
|
||||
];
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user