Using Service Classes in Laravel

Emre Ensar Çapcı
2 min readJun 15, 2024

--

Service classes separate business logic from controllers, making the code more organized, readable, and maintainable.

Why Should We Use Service Classes?

1. Reusability:

  • Encapsulates common business logic in one place, enabling reuse in different parts of the application.

2. Flexibility and Scalability:

  • A modular structure increases application flexibility and reduces the risk of breaking existing code when adding new features.

3. Dependency Injection:

  • Service classes can utilize dependency injection to manage dependencies, making the code more flexible and easier to manage.

4. Testability:

  • Isolates business logic, making it easier to write unit tests and achieve better test coverage.

In this article, we’ll walk through creating a CouponService, handling request validation, and using resources to format the output. Let’s dive in!

Step 1: Creating the Service Class

Laravel 11 introduced new Artisan commands. You can easily create a class using the command php artisan make:class Services/CouponService.

Step 2: Handling Request Validation

Create a new request class for handling coupon creation and updates:

php artisan make:request CouponRequest

Next, define the validation rules in the CouponRequest class:

Step 3: Creating a Resource

Let’s create a resource for our coupons.

php artisan make:resource CouponResource

Now, define how the coupon data should be formatted in the CouponResource class:

Step 4: Using the Service Class in the Controller

Finally, let’s use the service class, request validation, and resource in our controller.

By using service classes, request validation, and resources in Laravel, we can keep our controllers slim and focused, making our application more modular, testable, and maintainable. This approach not only helps in organizing the code but also makes it easier to scale and manage in the long run.

Feel free to implement these practices in your Laravel projects to enhance code quality and maintainability.

--

--