Featured image of post Organizing Services, Traits, and Helper Classes in Laravel 13

Organizing Services, Traits, and Helper Classes in Laravel 13

Understand where to put business logic, reusable traits, and helper classes in a Laravel 13 application.

Organizing Services, Traits, and Helper Classes in Laravel 13

As a Laravel application grows, placing all logic inside controllers makes the code harder to maintain.

Laravel’s app/ directory provides a flexible structure for separating business logic, reusable methods, and utility classes.

1. Use Services for Business Logic

The app/Services/ directory is suitable for classes that contain application-specific business logic.

Typical examples include:

  • Sending verification codes
  • Uploading files to Qiniu or other storage providers
  • Processing payments
  • Calling third-party APIs

You can create a service class with Artisan:

php artisan make:class Services/VerificationCodeService

For example:

<?php

namespace App\Services;

use Illuminate\Support\Facades\Cache;

class VerificationCodeService
{
    public function send(string $target, string $scene): int
    {
        $cacheKey = "verify_code:{$scene}:{$target}";

        if (Cache::has($cacheKey)) {
            throw new \RuntimeException(
                'Please try again later.',
                429
            );
        }

        $code = str_pad(
            (string) random_int(0, 999999),
            6,
            '0',
            STR_PAD_LEFT
        );

        Cache::put($cacheKey, $code, now()->addMinutes(5));

        // Integrate your email or SMS provider here.

        return 300;
    }
}

Controllers can receive the service through dependency injection instead of creating instances manually.

2. Use Traits for Reusable Methods

Traits are useful when multiple controllers or models need the same methods.

For example, an API response trait can provide consistent success and error responses.

Create it with:

php artisan make:trait ApiResponse

Place the file in app/Traits/ApiResponse.php:

<?php

namespace App\Traits;

use Illuminate\Http\JsonResponse;

trait ApiResponse
{
    protected function apiSuccess(
        mixed $data = null,
        string $message = 'Success',
        int $code = 200
    ): JsonResponse {
        return response()->json([
            'code' => $code,
            'message' => $message,
            'data' => $data,
        ]);
    }
}

Then include the trait in the base controller:

namespace App\Http\Controllers;

use App\Traits\ApiResponse;

abstract class Controller
{
    use ApiResponse;
}

Controllers extending this base class can now call $this->apiSuccess().

3. Use Support or Helpers for Utility Classes

For stateless utility classes, you can use either app/Support/ or app/Helpers/.

For example:

php artisan make:class Support/SignHelper
namespace App\Support;

class SignHelper
{
    public static function makeSignature(
        array $params,
        string $secret
    ): string {
        ksort($params);

        return md5(
            http_build_query($params) . '&key=' . $secret
        );
    }
}

Call it with:

use App\Support\SignHelper;

$sign = SignHelper::makeSignature($data, $secret);

4. Register Global Helper Functions (Optional)

If you prefer global functions, create app/helpers.php and register it in Composer’s autoload.files section:

"autoload": {
    "psr-4": {
        "App\\": "app/"
    },
    "files": [
        "app/helpers.php"
    ]
}

Then refresh Composer’s autoloader:

composer dump-autoload

Conclusion

A simple directory convention makes Laravel projects easier to understand:

  • Services: business logic and external integrations.
  • Traits: reusable methods shared by multiple classes.
  • Support or Helpers: stateless utility classes and helper functions.

Choose the location based on the responsibility of the code rather than creating directories without a clear purpose.

comments powered by Disqus