
Create APIs with Laravel 12 Resource Controllers
Yo, what’s good? If you’re tryna level up your Laravel game and build some fire APIs, you’re in the right spot. Today, we’re messing with Laravel 12 and its Resource Controllers, specifically, a CategoryController to handle categories like a boss. Think CRUD ops with JSON responses, all wrapped in that sweet Laravel magic. Let’s break it down, step by step, no cap.
Kick It Off with a Controller
First things first, we’re hitting the terminal like it’s our BFF. Run this bad boy:
Boom! Laravel’s Artisan just dropped a fresh CategoryController.php file in app/Http/Controllers. The --api flag? That’s the MVP move, it sets up five RESTful methods (index, store, show, update, destroy) without the extra fluff. No view nonsense, just pure API vibes. Check your folder, it’s sitting there, ready to flex.
Hook Up the Routes
Next up, we’re sliding into routes/api.php to wire this thing up. Pop in this code:Next up, we’re sliding into routes/api.php to wire this thing up. Pop in this code:
Real talk, this Route::apiResource line is straight fire. It links your CategoryController to the /api/categories endpoint and auto-maps those five methods to RESTful routes. You’re getting GET /categories, POST /categories, and all the rest with one line. Laravel’s out here doing the heavy lifting, respect.
Set Up the Controller
Now, let’s juice up that CategoryController with some real action.
Check the vibe:
- Index: Grabs all categories or throws a 404 if it’s empty, keepin’ it real.
- Store: Slaps a new category in the DB and flexes it back with a 200.
- Show: Finds one by ID or dips with a 404 if it’s a no-show.
- Update: Updates the name if it exists, smooth as butter.
- Destroy: Yeets a category and confirms it with swagger.
- This controller’s spitting JSON responses like a pro. You’re golden!
Test It with Postman
Time to see this baby shine. Fire up Postman (or whatever you rock with) and hit these endpoints. Assuming you’re running local, here’s the lineup:
API Endpoints for Testing
- GET http://localhost/api/categories
- POST http://localhost/api/categories
- GET http://localhost/api/categories/1
- PUT http://localhost/api/categories/1
- DELETE http://localhost/api/categories/1