A Step-by-Step Guide to API Versioning in Laravel 12

API versioning is crucial for maintaining backward compatibility while evolving your application. In this guide, we’ll implement a clean, scalable API versioning system in Laravel 12 using route prefixes, middleware, and versioned controllers.
 
🚀 Step 1: Setting Up API Versioning in Laravel
1. Configure the Base API Routes (routes/api.php) 
Instead of dumping all routes in one file, we split them into versioned route files.  
 
2. Create Version-Specific Route Files
 Store versioned routes in routes/api/v1.php and routes/api/v2.php.
 Example (routes/api/v1.php):
 

🛠️ Step 2: Organizing Versioned Controllers
Keep controllers separated by version: 
 

🔧 Step 3: Adding API Version Middleware
 
To track the API version in use, create a middleware:
 
Update the middleware (app/Http/Middleware/ApiVersionMiddleware.php):  
Register it in bootstrap/app.php: 
 
Apply middleware in routes (routes/api.php): 
 

✅ Step 4: Testing Versioned APIs
 
To run a single test file: 
 
To run a specific test method: 
 
Test Result: 
 
 
🚀 Final Thoughts & Best Practices
Use Semantic Versioning (v1, v2) – Helps track breaking changes.
Keep Controllers Thin – Delegate logic to services.
Document API Changes – Use Swagger/OpenAPI for each version.
 
📌 Conclusion
By following this structured approach, you can maintain multiple API versions cleanly in Laravel 12. This ensures backward compatibility while allowing smooth transitions to newer versions. 
💬 What’s your API versioning strategy? Let’s discuss in the comments!
 
📌 Liked this guide?
👉 Follow me on Medium for more Laravel & API development content! 

 Read More