Service Class in Laravel and usages.

Service classes are written to encapsulate codes and business logic separately from controllers. These classes should work for a service or operation. Unlike other classes, service classes do not inherit from other classes or controllers. Instead, the functions get called by object.

Convention:
  1. Should be stored under App\Services namespace.
  2. Should have “Service” as a name suffix. Example: PostService, CommentService etc.
Coding a Service Class
<?php

namespace App\Services;

class PostService
{
    public function store($data)
    {
        // Any logical block
        $post = Post::create($data);
        
        if ($post) {
            return $post;
        } else {
            throw new \Exception('Not stored. Something is wrong!');
        }
    }
}
Using the Functionality

Now from any controller, you can call the function store by an instance of PostService.

public function storePost(Request $request, PostService $service)
{
    // Some validation
    // Some data formatting and making an associative array.
    try {
        $service->store($insertionArray);
    } catch (\Exception $exception) {
        return response()->json(['error' => $exception->getMessage()], 422);
    }
    return response()->json([....], 200);
}

As you can see, in my service function I received data and stored it in the DB table, and if any issue happens I return an exception. The service should return the result to the controller, not to the view.

This is just a simple use case, you can go deeper with service classes. Definitely follow the More Documentation on Medium for details.

By: Toukir Ibn Azad 0 0