ProductController.php
app/Http/Controllers/ProductController.php
API Controller with Service Layer Integration
This controller demonstrates Laravel API best practices including:
• Dependency injection
• Service layer delegation
• Request validation
• Transaction management
• Resource transformation
• Consistent JSON responses
Complete Implementation
<?php namespace App\Http\Controllers; use App\Models\Product; use Illuminate\Http\Request; use Illuminate\Http\JsonResponse; use App\Http\Requests\ProductStoreRequest; use App\Http\Requests\ProductUpdateRequest; use Illuminate\Support\Facades\DB; use App\Services\ProductService; use App\Filters\ProductFilter; use App\Http\Resources\ProductResource; class ProductController extends Controller { protected $productService; protected $productFilter; public function __construct(ProductService $productService, ProductFilter $productFilter) { $this->productService = $productService; $this->productFilter = $productFilter; } public function index(Request $request): JsonResponse { try { // Centralized extraction of filters using the ProductFilter class $filters = $this->productFilter->getFilters(); // Delegate to the Service Layer to retrieve paginated products $products = $this->productService->getPaginatedProducts($filters); return response()->json([ 'success' => true, 'message' => 'Products retrieved successfully.', // Transform the collection of products using ProductResource 'data' => ProductResource::collection($products->items()), 'meta' => [ 'current_page' => $products->currentPage(), 'per_page' => $products->perPage(), 'total' => $products->total(), 'last_page' => $products->lastPage(), 'from' => $products->firstItem(), 'to' => $products->lastItem(), ] ], 200); // HTTP 200 OK } catch (\Exception $e) { // Log the error for debugging purposes logger()->error('Failed to retrieve products: ' . $e->getMessage(), ['exception' => $e]); return response()->json([ 'success' => false, 'message' => 'Failed to retrieve products.', 'error' => config('app.debug') ? $e->getMessage() : 'An unexpected error occurred.' ], 500); // HTTP 500 Internal Server Error } } public function store(ProductStoreRequest $request): JsonResponse { try { DB::beginTransaction(); // Start a database transaction // Delegate to the Service Layer to create the product $product = $this->productService->createProduct($request->validated()); DB::commit(); // Commit the transaction if all operations succeed return response()->json([ 'success' => true, 'message' => 'Product created successfully.', // Transform the single product using new ProductResource 'data' => new ProductResource($product) ], 201); // HTTP 201 Created } catch (\Exception $e) { DB::rollBack(); // Rollback the transaction on any error logger()->error('Failed to create product: ' . $e->getMessage(), ['exception' => $e]); return response()->json([ 'success' => false, 'message' => 'Failed to create product.', 'error' => config('app.debug') ? $e->getMessage() : 'An unexpected error occurred.' ], 500); // HTTP 500 Internal Server Error } } public function show(Product $product): JsonResponse { try { // Route Model Binding automatically resolves the Product instance. // No explicit service call needed for simple retrieval of an already resolved model. return response()->json([ 'success' => true, 'message' => 'Product retrieved successfully.', // Transform the single product using new ProductResource 'data' => new ProductResource($product) ], 200); // HTTP 200 OK } catch (\Exception $e) { // This catch might not be hit if Route Model Binding fails (Laravel typically throws 404 before this). // But kept for general error handling pattern. logger()->error('Product not found or error retrieving: ' . $e->getMessage(), ['exception' => $e, 'product_id' => $product->id ?? 'N/A']); return response()->json([ 'success' => false, 'message' => 'Product not found.', 'error' => config('app.debug') ? $e->getMessage() : 'The requested product could not be found.' ], 404); // HTTP 404 Not Found } } public function update(ProductUpdateRequest $request, Product $product): JsonResponse { try { DB::beginTransaction(); // Delegate to the Service Layer to update the product $updatedProduct = $this->productService->updateProduct($product, $request->validated()); DB::commit(); return response()->json([ 'success' => true, 'message' => 'Product updated successfully.', // Transform the updated product using new ProductResource 'data' => new ProductResource($updatedProduct) ], 200); // HTTP 200 OK } catch (\Exception $e) { DB::rollBack(); logger()->error('Failed to update product: ' . $e->getMessage(), ['exception' => $e, 'product_id' => $product->id]); return response()->json([ 'success' => false, 'message' => 'Failed to update product.', 'error' => config('app.debug') ? $e->getMessage() : 'An unexpected error occurred.' ], 500); // HTTP 500 Internal Server Error } } public function destroy(Product $product): JsonResponse { try { DB::beginTransaction(); // Delegate to the Service Layer to delete the product $this->productService->deleteProduct($product); DB::commit(); return response()->json([ 'success' => true, 'message' => 'Product deleted successfully.' ], 200); // HTTP 200 OK (alternatively, 204 No Content) } catch (\Exception $e) { DB::rollBack(); logger()->error('Failed to delete product: ' . $e->getMessage(), ['exception' => $e, 'product_id' => $product->id]); return response()->json([ 'success' => false, 'message' => 'Failed to delete product.', 'error' => config('app.debug') ? $e->getMessage() : 'An unexpected error occurred.' ], 500); // HTTP 500 Internal Server Error } } }
💡
Key Features
• Dependency injection for services
• Transaction management for data integrity
• Consistent JSON response structure
• Error handling with logging
• Resource transformation for consistent API output
• Filtering through dedicated filter class