๐Ÿ‘‰Basic Usage

How It Works?

When you need to create a listing API, the fetchAll method in BaseRepository manages the entire query process. This method interprets the query parameters passed from the frontend, apply but to interpret the flow you must follow repository pattern

Model

class User extends BaseModel
{
    public static function searchable(): array
    {
        return [
            "name",
            "slug",
        ];
    }
}

Controller

class UserController extends BaseController
{
    public function __construct(
        protected UserService $userService,
        protected UserResource $userResource,
        protected UserCollection $userCollection
    ) {
    }

    public function index(Request $request): JsonResponse
    {
        try {
            $filterable = $request->query();
            $users = $this->userService->index($filterable);
        } catch (Exception $exception) {
            return $this->handleException($exception);
        }

        return $this->successResponse(
            message: $this->lang("fetch-success"),
            payload: $this->userCollection->collection($users)
        );
    }
}

Service

class UserService extends BaseService
{
    public function __construct(
        protected UserRepositoryInterface $userRepository,
        protected ObjectMutable $objectMutable
    ) {
    }

    public function index(array $filterable = [], array $relationship = []): Collection|Paginator
    {
        $mutableBeforeData = $this->objectMutable->create([
            "filterable" => $filterable,
            "relationship" => $relationship
        ]);

        $this->interceptorEventDispatch(
            eventKey: "index.before",
            data: $mutableBeforeData
        );

        $filterable = $mutableBeforeData->get("filterable");
        $relationship = $mutableBeforeData->get("relationship");

        $users = $this->userRepository->fetchAll($filterable, $relationship);

        $this->objectMutable->create([
            "users" => $users,
        ]);

        $this->interceptorEventDispatch(
            eventKey: "index.after",
            data: $mutableAfterData
        );

        return $mutableAfterData->get("users");
    }
}

Query Parameters Format:

To leverage the Fluent Filterable feature, structure your request query parameters as follows:

/api/users/?filters[__in_id][0]=3&filters[__in_id][1]=6&filters[__in_id][2]=8

Generated Query

SELECT * FROM `users` WHERE `id` IN (3,6,8);

Last updated

Was this helpful?