











{"author":"Faiq Najib Al-Aziz","body":"\nWhile working on a PHP-to-Go migration, I audited the existing routes and controllers. Before moving them, I needed to see which patterns were worth keeping and which should go. The audit was eye-opening, hahaha.\n\nThe project profile looked like this:\n\n- **460+ routes** in `api.php`[^1]\n- **58 controllers** of various sizes and patterns\n- **5 auth guards**: `user-api`, `partner-api`, `open-api`, `open-api-limited`, `tms-api`\n- **Varied rate limiting**: from 3/minute up to 100/minute\n\nThis isn't a _\"how to build an API\"_ tutorial. It's a record of the patterns and anti-patterns I found, with examples of how they map to Go. If you're migrating or starting a project, I hope it helps you dodge a few mistakes I ran into first.\n\n## 1. Route Organization: Group with Intention\n\n### What I Found\n\nThe project actually had pretty well-structured route grouping. Auth guards were separated by domain:\n\n```php\n// routes/api.php - Good structure\nRoute::group(['middleware' =\u003e ['auth:user-api']], function() {\n    // 300+ routes for regular users\n});\n\nRoute::group(['middleware' =\u003e ['auth:partner-api']], function() {\n    // Routes for partners/resellers\n});\n\nRoute::group(['middleware' =\u003e ['auth:open-api']], function() {\n    // Routes for third-party integrations\n});\n```\n\nRate limiting was also applied with some thought:\n\n```php\n// Heavy AI analysis → strict rate limit\nRoute::get('/devices/get_aicam_reports_ai', 'DeviceController@getAiCamReportsAIAnalysis')\n    -\u003emiddleware('throttle:5,1');\n\n// Device commands → moderate rate limit\nRoute::post('/devices/{id}/cut_off_engine', 'DeviceController@sendFlameOffCommand')\n    -\u003emiddleware('throttle:10,1');\n\n// Google geocoding → relaxed rate limit (but still present)\nRoute::get('/google/reverse_geocode','GoogleController@reverseGeocodeLocation')\n    -\u003emiddleware('throttle:100,1');\n```\n\n### Problems Found\n\nBut yeah, there were issues:\n\n**Issue 1: Naming inconsistency.** Some routes used `snake_case`, others used `kebab-case`, and some used verbs:\n\n```php\n// All mixed together\nRoute::get('/device_geofence', ...);        // snake_case\nRoute::get('/all_devices', ...);             // snake_case\nRoute::put('/update_public_key', ...);       // verb + snake_case\nRoute::get('/shared_device', ...);           // snake_case, but public\nRoute::resource('devices', 'DeviceController'); // RESTful\nRoute::post('/devices/check_device_type', ...);  // verb under resource\n```\n\n**Issue 2: Controllers with too many responsibilities.** `DeviceController` had **40+ methods** and **2000+ lines of code**. CRUD, location tracking, reports, commands, dashboards, and AI, all in one. _One controller to rule them all_ hahaha.\n\n### Best Practice: Route Structure in Go\n\nIn this Go example, route groups and middleware are written explicitly:\n\n```go\n// internal/router/router.go\nfunc SetupRouter(\n    userHandler *handler.UserHandler,\n    deviceHandler *handler.DeviceHandler,\n    authMiddleware middleware.AuthMiddleware,\n    rateLimiter middleware.RateLimiter,\n) *gin.Engine {\n    r := gin.New()\n\n    // Public routes\n    r.POST(\"/login\", userHandler.Login)\n    r.POST(\"/register\", userHandler.Register)\n\n    // User API group\n    userAPI := r.Group(\"/\")\n    userAPI.Use(authMiddleware.Guard(\"user-api\"))\n    {\n        devices := userAPI.Group(\"/devices\")\n        {\n            devices.GET(\"\", deviceHandler.Index)\n            devices.GET(\"/:id\", deviceHandler.Show)\n            devices.POST(\"\", deviceHandler.Store)\n            devices.PUT(\"/:id\", deviceHandler.Update)\n            devices.DELETE(\"/:id\", deviceHandler.Destroy)\n\n            // Device actions (sub-group with rate limiter)\n            actions := devices.Group(\"/:id\")\n            actions.Use(rateLimiter.Limit(10, time.Minute))\n            {\n                actions.POST(\"/cut-off-engine\", deviceHandler.CutOffEngine)\n                actions.POST(\"/turn-on-engine\", deviceHandler.TurnOnEngine)\n            }\n        }\n    }\n\n    // Partner API group\n    partnerAPI := r.Group(\"/partner\")\n    partnerAPI.Use(authMiddleware.Guard(\"partner-api\"))\n    {\n        partnerAPI.POST(\"/user-submit\", partnerHandler.SubmitUser)\n        partnerAPI.POST(\"/generate-invoice\", partnerHandler.GenerateInvoice)\n    }\n\n    return r\n}\n```\n\nHere, each middleware chain and route group is code rather than array configuration. You can read the flow from top to bottom, and your IDE can jump straight to a handler's definition. The middleware for each route is visible right where the route is registered.\n\n## 2. Controller Pattern: Thin, Separated, Injected\n\n### Anti-Pattern: Fat Controller\n\nLet's look at real code from this project. This is the pattern that shows up most often (and should be **left behind**):\n\n```php\n// app/Http/Controllers/Auth/LoginController.php\n// Pattern: manual validation, business logic in controller\n\npublic function login(Request $request)\n{\n    // Manual validation in controller\n    $validator = Validator::make($request-\u003eall(),[\n        'email' =\u003e 'required|string',\n        'password' =\u003e 'required|string'\n    ]);\n\n    if($validator-\u003efails()){\n        return $this-\u003esendError('Validation Error.', 400, $validator-\u003eerrors());\n    }\n\n    // Business logic directly in controller\n    if ($this-\u003eattemptLogin($request)) {\n        $user = Auth::user();\n        $user-\u003egenerateToken();\n\n        if(isset($request-\u003eonesignal_user_id)){\n            $user-\u003esetOnesignalId($request-\u003eonesignal_user_id);\n        }\n\n        if($user-\u003eterminated){\n            return $this-\u003esendError('Sorry, This account has been terminated!' ,401);\n        }\n\n        $user-\u003eupdateLastLogin();\n        return $this-\u003esendResponse($user-\u003etoArray());\n    } else {\n        return $this-\u003esendError('Invalid username and password' ,401);\n    }\n}\n```\n\nIf the same login logic is needed elsewhere, such as in a CLI command or job queue, it has to be duplicated or extracted into a service. Easier to separate it from the start.\n\n### Anti-Pattern: Manual Permission Checks\n\nAnother example from `MaintenanceLogController`:\n\n```php\n// Permission check in every method, manually\nprivate function hasMaintenanceLogAccess()\n{\n    if (!$this-\u003euser || !$this-\u003euser-\u003erole) {\n        return false;\n    }\n    return $this-\u003euser-\u003erole_id == 1 || $this-\u003euser-\u003erole_id == 6;\n}\n\npublic function index(Request $request)\n{\n    if (!$this-\u003ehasMaintenanceLogAccess()) {\n        return $this-\u003esendError('You do not have permission', 403);\n    }\n    // ... logic\n}\n\npublic function store(Request $request)\n{\n    if (!$this-\u003ehasMaintenanceLogAccess()) {\n        return $this-\u003esendError('You do not have permission', 403);\n    }\n    // ... logic\n}\n\n// And so on in every method...\n```\n\nThis one fits a **Laravel Policy** or **Middleware** better. With 10 methods, why call and maintain the same check ten times? DRY (_Don't Repeat Yourself_)[^2] exists for exactly this.\n\n### Best Practice: Thin Controller + Service Layer\n\nIn the same project, one controller **already follows the right pattern**: `GeminiAIController`:\n\n```php\n// app/Http/Controllers/GeminiAIController.php\n// Pattern: Form Request + Service Injection + API Resource ✅\n\nclass GeminiAIController extends AuthenticatedController\n{\n    protected $geminiService;\n\n    public function __construct(GeminiAIService $geminiService)\n    {\n        parent::__construct();\n        $this-\u003egeminiService = $geminiService;  // Dependency Injection\n    }\n\n    public function analyzeDevice(GeminiAnalyzeDeviceRequest $request)  // Form Request\n    {\n        try {\n            $device = $this-\u003euser-\u003edevices()\n                -\u003ewhere('device_sn', $request-\u003einput('device_id'))\n                -\u003efirst();\n\n            if (!$device) {\n                return $this-\u003esendError('Device not found', 404);\n            }\n\n            $deviceData = $this-\u003eprepareDeviceData($device, ...);\n            $result = $this-\u003egeminiService-\u003eanalyzeDeviceData($deviceData, ...);  // Delegate to service\n\n            return $this-\u003esendResponse(new GeminiDeviceAnalysisResource($result));  // Resource transformation\n        } catch (\\Exception $e) {\n            return $this-\u003esendError($e-\u003egetMessage(), 500);\n        }\n    }\n}\n```\n\nThis pattern is worth copying:\n\n1. **Form Request** for validation (not `Validator::make()` in controller)\n2. **Service Injection** for business logic (not logic in controller)\n3. **API Resource** for response transformation (not raw `toArray()`)\n4. **Try-catch** only at the top level\n\n### Implementation in Go\n\nThe Go example below puts business logic in a service layer. Without Laravel's framework magic, dependencies and calls need to be wired explicitly:\n\n```go\n// internal/handler/auth_handler.go\ntype AuthHandler struct {\n    authService service.AuthService\n    validator   *validator.Validate\n}\n\nfunc NewAuthHandler(as service.AuthService, v *validator.Validate) *AuthHandler {\n    return \u0026AuthHandler{\n        authService: as,\n        validator:   v,\n    }\n}\n\n// Handler = thin: receive request, validate, call service, return response\nfunc (h *AuthHandler) Login(c *gin.Context) {\n    var req dto.LoginRequest\n    if err := c.ShouldBindJSON(\u0026req); err != nil {\n        response.Error(c, http.StatusBadRequest, \"Invalid request body\")\n        return\n    }\n\n    // Struct validation\n    if err := h.validator.Struct(req); err != nil {\n        response.ValidationError(c, err)\n        return\n    }\n\n    // Delegate to service\n    result, err := h.authService.Login(c.Request.Context(), req)\n    if err != nil {\n        switch {\n        case errors.Is(err, service.ErrInvalidCredentials):\n            response.Error(c, http.StatusUnauthorized, \"Invalid username or password\")\n        case errors.Is(err, service.ErrAccountTerminated):\n            response.Error(c, http.StatusUnauthorized, \"Account has been terminated\")\n        default:\n            response.Error(c, http.StatusInternalServerError, \"Internal server error\")\n        }\n        return\n    }\n\n    response.Success(c, result)\n}\n```\n\n```go\n// internal/service/auth_service.go\ntype AuthService interface {\n    Login(ctx context.Context, req dto.LoginRequest) (*dto.LoginResponse, error)\n}\n\ntype authService struct {\n    userRepo  repository.UserRepository\n    tokenRepo repository.TokenRepository\n}\n\nfunc (s *authService) Login(ctx context.Context, req dto.LoginRequest) (*dto.LoginResponse, error) {\n    user, err := s.userRepo.FindByEmail(ctx, req.Email)\n    if err != nil {\n        return nil, service.ErrInvalidCredentials\n    }\n\n    if err := bcrypt.CompareHashAndPassword(\n        []byte(user.Password), []byte(req.Password),\n    ); err != nil {\n        return nil, service.ErrInvalidCredentials\n    }\n\n    if user.Terminated {\n        return nil, service.ErrAccountTerminated\n    }\n\n    token, err := s.tokenRepo.Create(ctx, user.ID)\n    if err != nil {\n        return nil, err\n    }\n\n    return \u0026dto.LoginResponse{\n        User:  dto.NewUserResponse(user),\n        Token: token,\n    }, nil\n}\n```\n\nIn this example there's no inheritance, magic method, or constructor middleware. Dependencies are passed explicitly through dependency injection. Yes, it's more boilerplate (my fingers got tired, honestly), but each layer can be tested on its own and the data flow is easy to see.\n\n## 3. Validation: Consistent, One Approach, One Place\n\n### What I Found\n\nThe project used **three validation approaches** at the same time:\n\n**Approach 1: Manual `Validator::make()`** (most common, 80%+ of controllers):\n```php\n$validator = Validator::make($request-\u003eall(), [\n    'email' =\u003e 'required|string',\n    'password' =\u003e 'required|string'\n]);\nif($validator-\u003efails()){\n    return $this-\u003esendError('Validation Error.', 400, $validator-\u003eerrors());\n}\n```\n\n**Approach 2: Inline `$request-\u003evalidate()`**:\n```php\n$validated = $request-\u003evalidate([\n    'start_dt' =\u003e 'required|date',\n    'end_dt' =\u003e 'required|date|after_or_equal:start_dt',\n    'group_id' =\u003e 'nullable|integer',\n]);\n```\n\n**Approach 3: Form Request** (least used, but cleanest):\n```php\n// app/Http/Requests/GeminiAnalyzeDeviceRequest.php\nclass GeminiAnalyzeDeviceRequest extends FormRequest\n{\n    public function rules()\n    {\n        return [\n            'device_id' =\u003e 'required|string',\n            'analysis_type' =\u003e 'nullable|in:general,performance,behavior',\n            'date_range' =\u003e 'nullable|string',\n            'limit' =\u003e 'nullable|integer|min:1|max=1000',\n        ];\n    }\n}\n```\n\nWith approaches 1 and 2, the `device_id` rule can end up repeated across endpoints. When it changes, every copy needs an update (and one will surely be forgotten).\n\n### Best Practice\n\n**Use Form Requests for rules that need to be managed together.** The upsides:\n\n1. **Reusable**: one form request can serve several endpoints that use the same rules\n2. **Testable**: form requests can be tested independently without hitting endpoints\n3. **Readable**: all rules in one place, not scattered across controllers\n4. **Documentation**: a form request can be a source of information when building docs with tools like Swagger/L5-Swagger\n\n### Implementation in Go\n\nIn Go, validation uses struct tags:\n\n```go\n// internal/dto/request.go\ntype LoginRequest struct {\n    Email    string `json:\"email\" validate:\"required,email\"`\n    Password string `json:\"password\" validate:\"required,min=8\"`\n}\n\ntype AnalyzeDeviceRequest struct {\n    DeviceID     string `json:\"device_id\" validate:\"required\"`\n    AnalysisType string `json:\"analysis_type\" validate:\"omitempty,oneof=general performance behavior\"`\n    DateRange    string `json:\"date_range\" validate:\"omitempty\"`\n    Limit        int    `json:\"limit\" validate:\"omitempty,min=1,max=1000\"`\n}\n```\n\nIn this Go example, validation rules are written as struct tags and checked in the handler. The rules that apply sit right next to the request type.\n\n## 4. Response Consistency: One Format, All Endpoints\n\n### What I Found\n\nThe project had a decent base controller:\n\n```php\n// app/Http/Controllers/Controller.php\nclass Controller extends BaseController\n{\n    public function sendResponse($result = \"\", $message = \"OK\")\n    {\n        return response()-\u003ejson([\n            'success' =\u003e true,\n            'message' =\u003e $message,\n            'data' =\u003e $result,\n        ], 200);\n    }\n\n    public function sendError($error, $code = 400, $errorMessages = [])\n    {\n        $response = [\n            'success' =\u003e false,\n            'message' =\u003e $error,\n        ];\n        if(!empty($errorMessages)){\n            $response['errors'] = $errorMessages;\n        }\n        return response()-\u003ejson($response, $code);\n    }\n}\n```\n\nLooks good, right? But... there's an outlier:\n\n```php\n// loginOauth() uses a different format!\nreturn response()-\u003ejson([\n    'ResponseCode' =\u003e 0,           // ❌ different format\n    \"ResponseString\" =\u003e 'OK',      // ❌ different keys\n    \"data\" =\u003e new UserOauthResource($user)\n], 200);\n\n// While login() uses the standard format\nreturn $this-\u003esendResponse($user-\u003etoArray());  // ✅ consistent\n```\n\nImagine being the frontend developer handling two different response formats for essentially the same login endpoint. No wonder they'd ask, _\"why does it have to be like this?\"_ hahaha.\n\n### Best Practice\n\n**Aim for one response format across endpoints.** If you need versioning, use headers or URL prefixes rather than changing the response format.\n\n```php\n// Use API Resources consistently\nreturn $this-\u003esendResponse(new UserResource($user));\n\n// For collections with pagination\nreturn $this-\u003esendResponse([\n    'devices' =\u003e DeviceResource::collection($devices),\n    'meta' =\u003e new PaginationResource($devices),\n]);\n```\n\n### Implementation in Go\n\n```go\n// internal/pkg/response/response.go\ntype Response struct {\n    Success bool   `json:\"success\"`\n    Message string `json:\"message\"`\n    Data    any    `json:\"data,omitempty\"`\n    Errors  any    `json:\"errors,omitempty\"`\n}\n\nfunc Success(c *gin.Context, data any) {\n    c.JSON(http.StatusOK, Response{\n        Success: true,\n        Message: \"OK\",\n        Data:    data,\n    })\n}\n\nfunc Error(c *gin.Context, code int, message string) {\n    c.JSON(code, Response{\n        Success: false,\n        Message: message,\n    })\n}\n\nfunc ValidationError(c *gin.Context, err error) {\n    c.JSON(http.StatusBadRequest, Response{\n        Success: false,\n        Message: \"Validation Error\",\n        Errors:  formatValidationErrors(err),\n    })\n}\n```\n\nAs long as handlers use these helpers, the response shape is the same. `response.Success()` for success, `response.Error()` for errors. Done.\n\n## 5. Auth \u0026 Authorization: Guards, Not Manual Checks\n\n### What I Found\n\nThe project used five auth guards for different domains:\n\n```php\n// 5 guards for 5 different domains\nRoute::group(['middleware' =\u003e ['auth:user-api']], function() { ... });\nRoute::group(['middleware' =\u003e ['auth:partner-api']], function() { ... });\nRoute::group(['middleware' =\u003e ['auth:open-api']], function() { ... });\nRoute::group(['middleware' =\u003e ['auth:open-api-limited']], function() { ... });\nRoute::group(['middleware' =\u003e ['auth:tms-api']], function() { ... });\n```\n\nAnd a custom middleware for device-level authorization:\n\n```php\n// Device ownership check via middleware\nRoute::group(['middleware' =\u003e 'user_device_auth'], function() {\n    Route::resource('devices', 'DeviceController');\n    Route::get('/devices/{id}/last_location', 'DeviceController@lastLocation');\n    // ...\n});\n```\n\nThis is good. But the problem is in `AuthenticatedController`:\n\n```php\nclass AuthenticatedController extends Controller\n{\n    public function __construct()\n    {\n        $this-\u003emiddleware(function ($request, $next) {\n            // ❌ Manual token validation embedded in constructor\n            $this-\u003euser = Auth::guard('user-api')-\u003euser();\n            $token = $request-\u003ebearerToken();\n            $valid = Helper::validateToken($token);\n\n            if(!$valid){\n                return response()-\u003ejson(['error' =\u003e 'Invalid Token'], 401);\n            } elseif($this-\u003euser-\u003eterminated) {\n                return response()-\u003ejson(['message' =\u003e 'Sorry...'], 401);\n            } else {\n                return $next($request);\n            }\n        });\n    }\n}\n```\n\nWhy is this a problem? Because the token validation logic is stuck in the controller constructor, not in a dedicated middleware. As a result:\n\n- Can't be used in controllers that don't extend `AuthenticatedController`\n- Hard to test independently\n- If the logic changes, you have to modify this constructor\n\n### Best Practice\n\nSeparate concerns:\n\n```php\n// app/Http/Middleware/ValidateApiToken.php\nclass ValidateApiToken\n{\n    public function handle($request, Closure $next)\n    {\n        $token = $request-\u003ebearerToken();\n        if (!Helper::validateToken($token)) {\n            return response()-\u003ejson(['error' =\u003e 'Invalid Token'], 401);\n        }\n        return $next($request);\n    }\n}\n\n// app/Http/Middleware/CheckNotTerminated.php\nclass CheckNotTerminated\n{\n    public function handle($request, Closure $next)\n    {\n        $user = Auth::guard('user-api')-\u003euser();\n        if ($user-\u003eterminated) {\n            return response()-\u003ejson(['message' =\u003e 'Account terminated'], 401);\n        }\n        return $next($request);\n    }\n}\n```\n\nThis way, middleware can be composed and tested independently.\n\n### Implementation in Go\n\n```go\n// internal/middleware/auth.go\nfunc (m *AuthMiddleware) Guard(guardName string) gin.HandlerFunc {\n    return func(c *gin.Context) {\n        token := c.GetHeader(\"Authorization\")\n        if token == \"\" {\n            response.Error(c, http.StatusUnauthorized, \"Missing authorization token\")\n            c.Abort()\n            return\n        }\n\n        claims, err := m.tokenService.ValidateToken(c, token)\n        if err != nil {\n            response.Error(c, http.StatusUnauthorized, \"Invalid token\")\n            c.Abort()\n            return\n        }\n\n        // Guard-specific checks\n        switch guardName {\n        case \"user-api\":\n            if claims.Type != \"user\" {\n                response.Error(c, http.StatusForbidden, \"Invalid token type\")\n                c.Abort()\n                return\n            }\n            user, err := m.userRepo.FindByID(c, claims.UserID)\n            if err != nil || user.Terminated {\n                response.Error(c, http.StatusUnauthorized, \"Account terminated\")\n                c.Abort()\n                return\n            }\n            c.Set(\"user\", user)\n        case \"partner-api\":\n            // Partner-specific validation...\n        }\n\n        c.Next()\n    }\n}\n\n// Usage in router\nuserAPI := r.Group(\"/\")\nuserAPI.Use(authMiddleware.Guard(\"user-api\"))\n```\n\nIn Go, middleware is just a function you compose as needed, with no inheritance chain. The _composition over inheritance_[^3] principle fits this approach.\n\n## 6. Split Fat Controllers into Separate Handlers\n\n### The Big Problem\n\n`DeviceController` had **40+ methods**. A bug in the report feature meant scrolling past location, command, and dashboard code to find the relevant method. Hunting for one method among 1000+ lines is not a fun experience (trust me).\n\n### Solution: One Domain = One Handler\n\nTo separate responsibilities in Go, each handler can get its own struct:\n\n```go\n// internal/handler/device_handler.go - CRUD only\ntype DeviceHandler struct {\n    deviceService service.DeviceService\n}\n\nfunc (h *DeviceHandler) Index(c *gin.Context)   { ... }\nfunc (h *DeviceHandler) Show(c *gin.Context)    { ... }\nfunc (h *DeviceHandler) Store(c *gin.Context)   { ... }\nfunc (h *DeviceHandler) Update(c *gin.Context)  { ... }\nfunc (h *DeviceHandler) Destroy(c *gin.Context) { ... }\n\n// internal/handler/device_report_handler.go - Reports only\ntype DeviceReportHandler struct {\n    reportService service.DeviceReportService\n}\n\nfunc (h *DeviceReportHandler) GetSummaryRoute(c *gin.Context) { ... }\nfunc (h *DeviceReportHandler) GetStopReport(c *gin.Context)   { ... }\nfunc (h *DeviceReportHandler) GetFuelReport(c *gin.Context)   { ... }\n\n// internal/handler/device_command_handler.go - Commands only\ntype DeviceCommandHandler struct {\n    commandService service.DeviceCommandService\n}\n\nfunc (h *DeviceCommandHandler) CutOffEngine(c *gin.Context) { ... }\nfunc (h *DeviceCommandHandler) TurnOnEngine(c *gin.Context) { ... }\n```\n\n_Migration tip_: Before converting to Go, split PHP controllers into smaller handlers. Each handler will then have a clear scope when you start moving it.\n\n## Summary: Best Practice Checklist\n\nHere's the checklist from the patterns above:\n\n| Aspect | ❌ Don't | ✅ Do |\n|--------|----------|-------|\n| Validation | `Validator::make()` in controller | Form Request / struct tags |\n| Business Logic | Directly in controller | Separate into service layer |\n| Response | Different formats per endpoint | One consistent format |\n| Permission | Manual check in every method | Policy / Middleware |\n| Controller | One controller with 40+ methods | Split by domain |\n| Route naming | Mix of snake_case/kebab-case | Consistent single style |\n| Rate limiting | Only on \"dangerous\" routes | All expensive endpoints |\n| Auth | Logic in controller constructor | Dedicated middleware |\n\n## Closing\n\nWhat stuck with me most from this audit was **consistency**. In the codebase I looked at, a decent pattern used by everyone is easier to follow than hopping between patterns that are each supposedly perfect.\n\nIf you're staring at a codebase with 40 methods in one controller, three validation styles, and inconsistent response formats, relax, you're not alone. I found the same mix. Just start by fixing one pattern.\n\nIf you're migrating from PHP to Go, or want to start a new project with a tidier architecture, [get in touch](/en/contact/). Or check out my [services](/en/services/) to see how I can help.\n\nThanks for reading to the end!\n\n[^1]: This number includes public routes, authenticated routes, partner routes, and various integrations. Quite a lot to audit one by one.\n[^2]: DRY (Don't Repeat Yourself) is a simple principle that's easy to forget as a deadline approaches.\n[^3]: Composition over inheritance is the principle of building behavior from small components rather than deep inheritance trees. The Go examples above use this approach.\n","body_clean":"While working on a PHP-to-Go migration, I audited the existing routes and controllers. Before moving them, I needed to see which patterns were worth keeping and which should go. The audit was eye-opening, hahaha.\nThe project profile looked like this:\n460+ routes in api.php1 58 controllers of various sizes and patterns 5 auth guards: user-api, partner-api, open-api, open-api-limited, tms-api Varied rate limiting: from 3/minute up to 100/minute This isn\u0026rsquo;t a \u0026ldquo;how to build an API\u0026rdquo; tutorial. It\u0026rsquo;s a record of the patterns and anti-patterns I found, with examples of how they map to Go. If you\u0026rsquo;re migrating or starting a project, I hope it helps you dodge a few mistakes I ran into first.\n1. Route Organization: Group with Intention #What I Found #The project actually had pretty well-structured route grouping. Auth guards were separated by domain:\n// routes/api.php - Good structure Route::group([\u0026#39;middleware\u0026#39; =\u0026gt; [\u0026#39;auth:user-api\u0026#39;]], function() { // 300+ routes for regular users }); Route::group([\u0026#39;middleware\u0026#39; =\u0026gt; [\u0026#39;auth:partner-api\u0026#39;]], function() { // Routes for partners/resellers }); Route::group([\u0026#39;middleware\u0026#39; =\u0026gt; [\u0026#39;auth:open-api\u0026#39;]], function() { // Routes for third-party integrations }); Rate limiting was also applied with some thought:\n// Heavy AI analysis → strict rate limit Route::get(\u0026#39;/devices/get_aicam_reports_ai\u0026#39;, \u0026#39;DeviceController@getAiCamReportsAIAnalysis\u0026#39;) -\u0026gt;middleware(\u0026#39;throttle:5,1\u0026#39;); // Device commands → moderate rate limit Route::post(\u0026#39;/devices/{id}/cut_off_engine\u0026#39;, \u0026#39;DeviceController@sendFlameOffCommand\u0026#39;) -\u0026gt;middleware(\u0026#39;throttle:10,1\u0026#39;); // Google geocoding → relaxed rate limit (but still present) Route::get(\u0026#39;/google/reverse_geocode\u0026#39;,\u0026#39;GoogleController@reverseGeocodeLocation\u0026#39;) -\u0026gt;middleware(\u0026#39;throttle:100,1\u0026#39;); Problems Found #But yeah, there were issues:\nIssue 1: Naming inconsistency. Some routes used snake_case, others used kebab-case, and some used verbs:\n// All mixed together Route::get(\u0026#39;/device_geofence\u0026#39;, ...); // snake_case Route::get(\u0026#39;/all_devices\u0026#39;, ...); // snake_case Route::put(\u0026#39;/update_public_key\u0026#39;, ...); // verb + snake_case Route::get(\u0026#39;/shared_device\u0026#39;, ...); // snake_case, but public Route::resource(\u0026#39;devices\u0026#39;, \u0026#39;DeviceController\u0026#39;); // RESTful Route::post(\u0026#39;/devices/check_device_type\u0026#39;, ...); // verb under resource Issue 2: Controllers with too many responsibilities. DeviceController had 40+ methods and 2000+ lines of code. CRUD, location tracking, reports, commands, dashboards, and AI, all in one. One controller to rule them all hahaha.\nBest Practice: Route Structure in Go #In this Go example, route groups and middleware are written explicitly:\n// internal/router/router.go func SetupRouter( userHandler *handler.UserHandler, deviceHandler *handler.DeviceHandler, authMiddleware middleware.AuthMiddleware, rateLimiter middleware.RateLimiter, ) *gin.Engine { r := gin.New() // Public routes r.POST(\u0026#34;/login\u0026#34;, userHandler.Login) r.POST(\u0026#34;/register\u0026#34;, userHandler.Register) // User API group userAPI := r.Group(\u0026#34;/\u0026#34;) userAPI.Use(authMiddleware.Guard(\u0026#34;user-api\u0026#34;)) { devices := userAPI.Group(\u0026#34;/devices\u0026#34;) { devices.GET(\u0026#34;\u0026#34;, deviceHandler.Index) devices.GET(\u0026#34;/:id\u0026#34;, deviceHandler.Show) devices.POST(\u0026#34;\u0026#34;, deviceHandler.Store) devices.PUT(\u0026#34;/:id\u0026#34;, deviceHandler.Update) devices.DELETE(\u0026#34;/:id\u0026#34;, deviceHandler.Destroy) // Device actions (sub-group with rate limiter) actions := devices.Group(\u0026#34;/:id\u0026#34;) actions.Use(rateLimiter.Limit(10, time.Minute)) { actions.POST(\u0026#34;/cut-off-engine\u0026#34;, deviceHandler.CutOffEngine) actions.POST(\u0026#34;/turn-on-engine\u0026#34;, deviceHandler.TurnOnEngine) } } } // Partner API group partnerAPI := r.Group(\u0026#34;/partner\u0026#34;) partnerAPI.Use(authMiddleware.Guard(\u0026#34;partner-api\u0026#34;)) { partnerAPI.POST(\u0026#34;/user-submit\u0026#34;, partnerHandler.SubmitUser) partnerAPI.POST(\u0026#34;/generate-invoice\u0026#34;, partnerHandler.GenerateInvoice) } return r } Here, each middleware chain and route group is code rather than array configuration. You can read the flow from top to bottom, and your IDE can jump straight to a handler\u0026rsquo;s definition. The middleware for each route is visible right where the route is registered.\n2. Controller Pattern: Thin, Separated, Injected #Anti-Pattern: Fat Controller #Let\u0026rsquo;s look at real code from this project. This is the pattern that shows up most often (and should be left behind):\n// app/Http/Controllers/Auth/LoginController.php // Pattern: manual validation, business logic in controller public function login(Request $request) { // Manual validation in controller $validator = Validator::make($request-\u0026gt;all(),[ \u0026#39;email\u0026#39; =\u0026gt; \u0026#39;required|string\u0026#39;, \u0026#39;password\u0026#39; =\u0026gt; \u0026#39;required|string\u0026#39; ]); if($validator-\u0026gt;fails()){ return $this-\u0026gt;sendError(\u0026#39;Validation Error.\u0026#39;, 400, $validator-\u0026gt;errors()); } // Business logic directly in controller if ($this-\u0026gt;attemptLogin($request)) { $user = Auth::user(); $user-\u0026gt;generateToken(); if(isset($request-\u0026gt;onesignal_user_id)){ $user-\u0026gt;setOnesignalId($request-\u0026gt;onesignal_user_id); } if($user-\u0026gt;terminated){ return $this-\u0026gt;sendError(\u0026#39;Sorry, This account has been terminated!\u0026#39; ,401); } $user-\u0026gt;updateLastLogin(); return $this-\u0026gt;sendResponse($user-\u0026gt;toArray()); } else { return $this-\u0026gt;sendError(\u0026#39;Invalid username and password\u0026#39; ,401); } } If the same login logic is needed elsewhere, such as in a CLI command or job queue, it has to be duplicated or extracted into a service. Easier to separate it from the start.\nAnti-Pattern: Manual Permission Checks #Another example from MaintenanceLogController:\n// Permission check in every method, manually private function hasMaintenanceLogAccess() { if (!$this-\u0026gt;user || !$this-\u0026gt;user-\u0026gt;role) { return false; } return $this-\u0026gt;user-\u0026gt;role_id == 1 || $this-\u0026gt;user-\u0026gt;role_id == 6; } public function index(Request $request) { if (!$this-\u0026gt;hasMaintenanceLogAccess()) { return $this-\u0026gt;sendError(\u0026#39;You do not have permission\u0026#39;, 403); } // ... logic } public function store(Request $request) { if (!$this-\u0026gt;hasMaintenanceLogAccess()) { return $this-\u0026gt;sendError(\u0026#39;You do not have permission\u0026#39;, 403); } // ... logic } // And so on in every method... This one fits a Laravel Policy or Middleware better. With 10 methods, why call and maintain the same check ten times? DRY (Don\u0026rsquo;t Repeat Yourself)2 exists for exactly this.\nBest Practice: Thin Controller + Service Layer #In the same project, one controller already follows the right pattern: GeminiAIController:\n// app/Http/Controllers/GeminiAIController.php // Pattern: Form Request + Service Injection + API Resource ✅ class GeminiAIController extends AuthenticatedController { protected $geminiService; public function __construct(GeminiAIService $geminiService) { parent::__construct(); $this-\u0026gt;geminiService = $geminiService; // Dependency Injection } public function analyzeDevice(GeminiAnalyzeDeviceRequest $request) // Form Request { try { $device = $this-\u0026gt;user-\u0026gt;devices() -\u0026gt;where(\u0026#39;device_sn\u0026#39;, $request-\u0026gt;input(\u0026#39;device_id\u0026#39;)) -\u0026gt;first(); if (!$device) { return $this-\u0026gt;sendError(\u0026#39;Device not found\u0026#39;, 404); } $deviceData = $this-\u0026gt;prepareDeviceData($device, ...); $result = $this-\u0026gt;geminiService-\u0026gt;analyzeDeviceData($deviceData, ...); // Delegate to service return $this-\u0026gt;sendResponse(new GeminiDeviceAnalysisResource($result)); // Resource transformation } catch (\\Exception $e) { return $this-\u0026gt;sendError($e-\u0026gt;getMessage(), 500); } } } This pattern is worth copying:\nForm Request for validation (not Validator::make() in controller) Service Injection for business logic (not logic in controller) API Resource for response transformation (not raw toArray()) Try-catch only at the top level Implementation in Go #The Go example below puts business logic in a service layer. Without Laravel\u0026rsquo;s framework magic, dependencies and calls need to be wired explicitly:\n// internal/handler/auth_handler.go type AuthHandler struct { authService service.AuthService validator *validator.Validate } func NewAuthHandler(as service.AuthService, v *validator.Validate) *AuthHandler { return \u0026amp;AuthHandler{ authService: as, validator: v, } } // Handler = thin: receive request, validate, call service, return response func (h *AuthHandler) Login(c *gin.Context) { var req dto.LoginRequest if err := c.ShouldBindJSON(\u0026amp;req); err != nil { response.Error(c, http.StatusBadRequest, \u0026#34;Invalid request body\u0026#34;) return } // Struct validation if err := h.validator.Struct(req); err != nil { response.ValidationError(c, err) return } // Delegate to service result, err := h.authService.Login(c.Request.Context(), req) if err != nil { switch { case errors.Is(err, service.ErrInvalidCredentials): response.Error(c, http.StatusUnauthorized, \u0026#34;Invalid username or password\u0026#34;) case errors.Is(err, service.ErrAccountTerminated): response.Error(c, http.StatusUnauthorized, \u0026#34;Account has been terminated\u0026#34;) default: response.Error(c, http.StatusInternalServerError, \u0026#34;Internal server error\u0026#34;) } return } response.Success(c, result) } // internal/service/auth_service.go type AuthService interface { Login(ctx context.Context, req dto.LoginRequest) (*dto.LoginResponse, error) } type authService struct { userRepo repository.UserRepository tokenRepo repository.TokenRepository } func (s *authService) Login(ctx context.Context, req dto.LoginRequest) (*dto.LoginResponse, error) { user, err := s.userRepo.FindByEmail(ctx, req.Email) if err != nil { return nil, service.ErrInvalidCredentials } if err := bcrypt.CompareHashAndPassword( []byte(user.Password), []byte(req.Password), ); err != nil { return nil, service.ErrInvalidCredentials } if user.Terminated { return nil, service.ErrAccountTerminated } token, err := s.tokenRepo.Create(ctx, user.ID) if err != nil { return nil, err } return \u0026amp;dto.LoginResponse{ User: dto.NewUserResponse(user), Token: token, }, nil } In this example there\u0026rsquo;s no inheritance, magic method, or constructor middleware. Dependencies are passed explicitly through dependency injection. Yes, it\u0026rsquo;s more boilerplate (my fingers got tired, honestly), but each layer can be tested on its own and the data flow is easy to see.\n3. Validation: Consistent, One Approach, One Place #What I Found #The project used three validation approaches at the same time:\nApproach 1: Manual Validator::make() (most common, 80%+ of controllers):\n$validator = Validator::make($request-\u0026gt;all(), [ \u0026#39;email\u0026#39; =\u0026gt; \u0026#39;required|string\u0026#39;, \u0026#39;password\u0026#39; =\u0026gt; \u0026#39;required|string\u0026#39; ]); if($validator-\u0026gt;fails()){ return $this-\u0026gt;sendError(\u0026#39;Validation Error.\u0026#39;, 400, $validator-\u0026gt;errors()); } Approach 2: Inline $request-\u0026gt;validate():\n$validated = $request-\u0026gt;validate([ \u0026#39;start_dt\u0026#39; =\u0026gt; \u0026#39;required|date\u0026#39;, \u0026#39;end_dt\u0026#39; =\u0026gt; \u0026#39;required|date|after_or_equal:start_dt\u0026#39;, \u0026#39;group_id\u0026#39; =\u0026gt; \u0026#39;nullable|integer\u0026#39;, ]); Approach 3: Form Request (least used, but cleanest):\n// app/Http/Requests/GeminiAnalyzeDeviceRequest.php class GeminiAnalyzeDeviceRequest extends FormRequest { public function rules() { return [ \u0026#39;device_id\u0026#39; =\u0026gt; \u0026#39;required|string\u0026#39;, \u0026#39;analysis_type\u0026#39; =\u0026gt; \u0026#39;nullable|in:general,performance,behavior\u0026#39;, \u0026#39;date_range\u0026#39; =\u0026gt; \u0026#39;nullable|string\u0026#39;, \u0026#39;limit\u0026#39; =\u0026gt; \u0026#39;nullable|integer|min:1|max=1000\u0026#39;, ]; } } With approaches 1 and 2, the device_id rule can end up repeated across endpoints. When it changes, every copy needs an update (and one will surely be forgotten).\nBest Practice #Use Form Requests for rules that need to be managed together. The upsides:\nReusable: one form request can serve several endpoints that use the same rules Testable: form requests can be tested independently without hitting endpoints Readable: all rules in one place, not scattered across controllers Documentation: a form request can be a source of information when building docs with tools like Swagger/L5-Swagger Implementation in Go #In Go, validation uses struct tags:\n// internal/dto/request.go type LoginRequest struct { Email string `json:\u0026#34;email\u0026#34; validate:\u0026#34;required,email\u0026#34;` Password string `json:\u0026#34;password\u0026#34; validate:\u0026#34;required,min=8\u0026#34;` } type AnalyzeDeviceRequest struct { DeviceID string `json:\u0026#34;device_id\u0026#34; validate:\u0026#34;required\u0026#34;` AnalysisType string `json:\u0026#34;analysis_type\u0026#34; validate:\u0026#34;omitempty,oneof=general performance behavior\u0026#34;` DateRange string `json:\u0026#34;date_range\u0026#34; validate:\u0026#34;omitempty\u0026#34;` Limit int `json:\u0026#34;limit\u0026#34; validate:\u0026#34;omitempty,min=1,max=1000\u0026#34;` } In this Go example, validation rules are written as struct tags and checked in the handler. The rules that apply sit right next to the request type.\n4. Response Consistency: One Format, All Endpoints #What I Found #The project had a decent base controller:\n// app/Http/Controllers/Controller.php class Controller extends BaseController { public function sendResponse($result = \u0026#34;\u0026#34;, $message = \u0026#34;OK\u0026#34;) { return response()-\u0026gt;json([ \u0026#39;success\u0026#39; =\u0026gt; true, \u0026#39;message\u0026#39; =\u0026gt; $message, \u0026#39;data\u0026#39; =\u0026gt; $result, ], 200); } public function sendError($error, $code = 400, $errorMessages = []) { $response = [ \u0026#39;success\u0026#39; =\u0026gt; false, \u0026#39;message\u0026#39; =\u0026gt; $error, ]; if(!empty($errorMessages)){ $response[\u0026#39;errors\u0026#39;] = $errorMessages; } return response()-\u0026gt;json($response, $code); } } Looks good, right? But\u0026hellip; there\u0026rsquo;s an outlier:\n// loginOauth() uses a different format! return response()-\u0026gt;json([ \u0026#39;ResponseCode\u0026#39; =\u0026gt; 0, // ❌ different format \u0026#34;ResponseString\u0026#34; =\u0026gt; \u0026#39;OK\u0026#39;, // ❌ different keys \u0026#34;data\u0026#34; =\u0026gt; new UserOauthResource($user) ], 200); // While login() uses the standard format return $this-\u0026gt;sendResponse($user-\u0026gt;toArray()); // ✅ consistent Imagine being the frontend developer handling two different response formats for essentially the same login endpoint. No wonder they\u0026rsquo;d ask, \u0026ldquo;why does it have to be like this?\u0026rdquo; hahaha.\nBest Practice #Aim for one response format across endpoints. If you need versioning, use headers or URL prefixes rather than changing the response format.\n// Use API Resources consistently return $this-\u0026gt;sendResponse(new UserResource($user)); // For collections with pagination return $this-\u0026gt;sendResponse([ \u0026#39;devices\u0026#39; =\u0026gt; DeviceResource::collection($devices), \u0026#39;meta\u0026#39; =\u0026gt; new PaginationResource($devices), ]); Implementation in Go #// internal/pkg/response/response.go type Response struct { Success bool `json:\u0026#34;success\u0026#34;` Message string `json:\u0026#34;message\u0026#34;` Data any `json:\u0026#34;data,omitempty\u0026#34;` Errors any `json:\u0026#34;errors,omitempty\u0026#34;` } func Success(c *gin.Context, data any) { c.JSON(http.StatusOK, Response{ Success: true, Message: \u0026#34;OK\u0026#34;, Data: data, }) } func Error(c *gin.Context, code int, message string) { c.JSON(code, Response{ Success: false, Message: message, }) } func ValidationError(c *gin.Context, err error) { c.JSON(http.StatusBadRequest, Response{ Success: false, Message: \u0026#34;Validation Error\u0026#34;, Errors: formatValidationErrors(err), }) } As long as handlers use these helpers, the response shape is the same. response.Success() for success, response.Error() for errors. Done.\n5. Auth \u0026amp; Authorization: Guards, Not Manual Checks #What I Found #The project used five auth guards for different domains:\n// 5 guards for 5 different domains Route::group([\u0026#39;middleware\u0026#39; =\u0026gt; [\u0026#39;auth:user-api\u0026#39;]], function() { ... }); Route::group([\u0026#39;middleware\u0026#39; =\u0026gt; [\u0026#39;auth:partner-api\u0026#39;]], function() { ... }); Route::group([\u0026#39;middleware\u0026#39; =\u0026gt; [\u0026#39;auth:open-api\u0026#39;]], function() { ... }); Route::group([\u0026#39;middleware\u0026#39; =\u0026gt; [\u0026#39;auth:open-api-limited\u0026#39;]], function() { ... }); Route::group([\u0026#39;middleware\u0026#39; =\u0026gt; [\u0026#39;auth:tms-api\u0026#39;]], function() { ... }); And a custom middleware for device-level authorization:\n// Device ownership check via middleware Route::group([\u0026#39;middleware\u0026#39; =\u0026gt; \u0026#39;user_device_auth\u0026#39;], function() { Route::resource(\u0026#39;devices\u0026#39;, \u0026#39;DeviceController\u0026#39;); Route::get(\u0026#39;/devices/{id}/last_location\u0026#39;, \u0026#39;DeviceController@lastLocation\u0026#39;); // ... }); This is good. But the problem is in AuthenticatedController:\nclass AuthenticatedController extends Controller { public function __construct() { $this-\u0026gt;middleware(function ($request, $next) { // ❌ Manual token validation embedded in constructor $this-\u0026gt;user = Auth::guard(\u0026#39;user-api\u0026#39;)-\u0026gt;user(); $token = $request-\u0026gt;bearerToken(); $valid = Helper::validateToken($token); if(!$valid){ return response()-\u0026gt;json([\u0026#39;error\u0026#39; =\u0026gt; \u0026#39;Invalid Token\u0026#39;], 401); } elseif($this-\u0026gt;user-\u0026gt;terminated) { return response()-\u0026gt;json([\u0026#39;message\u0026#39; =\u0026gt; \u0026#39;Sorry...\u0026#39;], 401); } else { return $next($request); } }); } } Why is this a problem? Because the token validation logic is stuck in the controller constructor, not in a dedicated middleware. As a result:\nCan\u0026rsquo;t be used in controllers that don\u0026rsquo;t extend AuthenticatedController Hard to test independently If the logic changes, you have to modify this constructor Best Practice #Separate concerns:\n// app/Http/Middleware/ValidateApiToken.php class ValidateApiToken { public function handle($request, Closure $next) { $token = $request-\u0026gt;bearerToken(); if (!Helper::validateToken($token)) { return response()-\u0026gt;json([\u0026#39;error\u0026#39; =\u0026gt; \u0026#39;Invalid Token\u0026#39;], 401); } return $next($request); } } // app/Http/Middleware/CheckNotTerminated.php class CheckNotTerminated { public function handle($request, Closure $next) { $user = Auth::guard(\u0026#39;user-api\u0026#39;)-\u0026gt;user(); if ($user-\u0026gt;terminated) { return response()-\u0026gt;json([\u0026#39;message\u0026#39; =\u0026gt; \u0026#39;Account terminated\u0026#39;], 401); } return $next($request); } } This way, middleware can be composed and tested independently.\nImplementation in Go #// internal/middleware/auth.go func (m *AuthMiddleware) Guard(guardName string) gin.HandlerFunc { return func(c *gin.Context) { token := c.GetHeader(\u0026#34;Authorization\u0026#34;) if token == \u0026#34;\u0026#34; { response.Error(c, http.StatusUnauthorized, \u0026#34;Missing authorization token\u0026#34;) c.Abort() return } claims, err := m.tokenService.ValidateToken(c, token) if err != nil { response.Error(c, http.StatusUnauthorized, \u0026#34;Invalid token\u0026#34;) c.Abort() return } // Guard-specific checks switch guardName { case \u0026#34;user-api\u0026#34;: if claims.Type != \u0026#34;user\u0026#34; { response.Error(c, http.StatusForbidden, \u0026#34;Invalid token type\u0026#34;) c.Abort() return } user, err := m.userRepo.FindByID(c, claims.UserID) if err != nil || user.Terminated { response.Error(c, http.StatusUnauthorized, \u0026#34;Account terminated\u0026#34;) c.Abort() return } c.Set(\u0026#34;user\u0026#34;, user) case \u0026#34;partner-api\u0026#34;: // Partner-specific validation... } c.Next() } } // Usage in router userAPI := r.Group(\u0026#34;/\u0026#34;) userAPI.Use(authMiddleware.Guard(\u0026#34;user-api\u0026#34;)) In Go, middleware is just a function you compose as needed, with no inheritance chain. The composition over inheritance3 principle fits this approach.\n6. Split Fat Controllers into Separate Handlers #The Big Problem #DeviceController had 40+ methods. A bug in the report feature meant scrolling past location, command, and dashboard code to find the relevant method. Hunting for one method among 1000+ lines is not a fun experience (trust me).\nSolution: One Domain = One Handler #To separate responsibilities in Go, each handler can get its own struct:\n// internal/handler/device_handler.go - CRUD only type DeviceHandler struct { deviceService service.DeviceService } func (h *DeviceHandler) Index(c *gin.Context) { ... } func (h *DeviceHandler) Show(c *gin.Context) { ... } func (h *DeviceHandler) Store(c *gin.Context) { ... } func (h *DeviceHandler) Update(c *gin.Context) { ... } func (h *DeviceHandler) Destroy(c *gin.Context) { ... } // internal/handler/device_report_handler.go - Reports only type DeviceReportHandler struct { reportService service.DeviceReportService } func (h *DeviceReportHandler) GetSummaryRoute(c *gin.Context) { ... } func (h *DeviceReportHandler) GetStopReport(c *gin.Context) { ... } func (h *DeviceReportHandler) GetFuelReport(c *gin.Context) { ... } // internal/handler/device_command_handler.go - Commands only type DeviceCommandHandler struct { commandService service.DeviceCommandService } func (h *DeviceCommandHandler) CutOffEngine(c *gin.Context) { ... } func (h *DeviceCommandHandler) TurnOnEngine(c *gin.Context) { ... } Migration tip: Before converting to Go, split PHP controllers into smaller handlers. Each handler will then have a clear scope when you start moving it.\nSummary: Best Practice Checklist #Here\u0026rsquo;s the checklist from the patterns above:\nAspect ❌ Don\u0026rsquo;t ✅ Do Validation Validator::make() in controller Form Request / struct tags Business Logic Directly in controller Separate into service layer Response Different formats per endpoint One consistent format Permission Manual check in every method Policy / Middleware Controller One controller with 40+ methods Split by domain Route naming Mix of snake_case/kebab-case Consistent single style Rate limiting Only on \u0026ldquo;dangerous\u0026rdquo; routes All expensive endpoints Auth Logic in controller constructor Dedicated middleware Closing #What stuck with me most from this audit was consistency. In the codebase I looked at, a decent pattern used by everyone is easier to follow than hopping between patterns that are each supposedly perfect.\nIf you\u0026rsquo;re staring at a codebase with 40 methods in one controller, three validation styles, and inconsistent response formats, relax, you\u0026rsquo;re not alone. I found the same mix. Just start by fixing one pattern.\nIf you\u0026rsquo;re migrating from PHP to Go, or want to start a new project with a tidier architecture, get in touch. Or check out my services to see how I can help.\nThanks for reading to the end!\nThis number includes public routes, authenticated routes, partner routes, and various integrations. Quite a lot to audit one by one.\u0026#160;\u0026#x21a9;\u0026#xfe0e;\nDRY (Don\u0026rsquo;t Repeat Yourself) is a simple principle that\u0026rsquo;s easy to forget as a deadline approaches.\u0026#160;\u0026#x21a9;\u0026#xfe0e;\nComposition over inheritance is the principle of building behavior from small components rather than deep inheritance trees. The Go examples above use this approach.\u0026#160;\u0026#x21a9;\u0026#xfe0e;\n","canonical":"https://najib.id/en/writing/2026/laravel-go-api-best-practice/","description":"Notes from auditing 460+ routes and 58 controllers in a PHP-to-Go migration: patterns worth keeping, patterns to ditch, and how each maps to Go.","language":"en","lastmod":"2026-11-11T23:31:00Z","publishedAt":"2026-05-07T10:28:00Z","readingTime":12,"section":"writing","series":null,"tags":["go","php","laravel","api","architecture"],"title":"Best Practices for Building APIs in Laravel and Go: Notes from a Real Project","type":"writing","url":"https://najib.id/en/writing/2026/laravel-go-api-best-practice/","wordCount":2545}
