Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Laravel Api Helpers Laravel Package

mahmoud-almalah/laravel-api-helpers

A lightweight Laravel package with practical helpers for building cleaner APIs. Reduce boilerplate, standardize common response and controller patterns, and keep your backend code consistent, readable, and easier to maintain across projects.

View on GitHub
Deep Wiki
Context7

Getting Started

  • composer require mahmoud-almalah/laravel-api-helpers — the service provider is auto-discovered, so there is nothing to register in config/app.php or bootstrap/providers.php.
  • Requirements: PHP ^8.1 and Laravel 10, 11, or 12. Check composer.json constraints before adopting on a mixed-version monorepo.
  • Read the README first; it is the authoritative source since v1.0.0 ships no configuration file and no published docs site.
  • The package exposes three response classes under MahmoudAlmalah\LaravelApiHelpers\Responses:
    • SuccessResponse — single resource / simple payloads
    • ErrorResponse — error envelopes
    • CollectionResponse — collections, with or without pagination
  • First use case: standardize a controller's JSON output. The release note example is the canonical starting point:
use MahmoudAlmalah\LaravelApiHelpers\Responses\CollectionResponse;
use App\Http\Resources\UserResource;

return new CollectionResponse(
    key: 'users',
    collection: UserResource::collection(User::all()),
    paginator: null,
    message: 'Users fetched successfully'
);
  • Start by wiring it into a single controller (e.g. UserController@index) and writing one feature test to pin down the exact JSON envelope (status, data vs key, meta, message). The v1.0.0 release notes describe the constructors but not the full response shape, so test the actual contract.

Implementation Patterns

  • Wrap resources, don't inline models. The classes integrate with Laravel Resource / ResourceCollection instances. Always pass UserResource::collection(...) or new UserResource($user) — not raw Eloquent results — so transformation logic stays in one place.
  • Use named arguments. The CollectionResponse constructor mixes key, collection, paginator, and message; positional arguments are easy to get wrong and named args match the README exactly.
  • Collection with pagination. Paginate the query first, then pass the paginator into the response rather than letting the resource collection re-paginate:
$users = User::query()->paginate(25);

return new CollectionResponse(
    key: 'users',
    collection: UserResource::collection($users->getCollection()),
    paginator: $users,
    message: 'Users fetched successfully'
);

Confirm the exact paginator shape the package expects (a LengthAwarePaginator vs the original paginator) once in a test.

  • Single-resource endpoints map to SuccessResponse; typically return new SuccessResponse(data: new UserResource($user), message: '...').
  • Error uniforming. Return ErrorResponse from bootstrap/app.php's withExceptions() closure to give API consumers the same envelope for validation, 404s, and auth failures:
->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(function (Throwable $e, $request) {
        if ($request->is('api/*')) {
            return new ErrorResponse(message: $e->getMessage(), status: 500);
        }
    });
})

Verify the exact constructor signature before relying on status — the release notes don't list ErrorResponse parameters.

  • Consistent controller responses. Create a small ApiController base or trait with helpers (respondSuccess(), respondError(), respondCollection()) that wrap these classes. This keeps controllers readable and isolates any future package changes to one file.
  • Extensibility. The release notes call out a ResponseInterface and service class. If your API needs a different envelope (e.g. always data + meta + links, or a custom trace_id), implement ResponseInterface in your own class rather than subclassing the shipped responses — safer for upgrades.
  • Typical workflow:
    1. Add the package, build one controller with the three helpers.
    2. Write snapshot/feature tests for the JSON contract.
    3. Refactor existing response()->json(...) calls to the new classes behind those tests.
    4. Move error handling into withExceptions() last, since it affects every endpoint.

Gotchas and Tips

  • No config in v1.0.0. There is nothing to publish (vendor:publish will do nothing meaningful) and no per-project envelope configuration. If you need keys or envelopes other than what ships, you must extend via ResponseInterface.
  • Pagination is a separate argument. Passing UserResource::collection(User::paginate()) and a paginator will likely duplicate the meta block or paginate twice. Fetch the builder's collection and paginator separately, and test the paginated case explicitly.
  • Response class behavior. The examples return new ... from controllers, which implies the classes return JSON via toResponse() or Jsonable. Verify with $response->getStatusCode() and $response->getContent() in tests — especially the default status for SuccessResponse (likely 200) and ErrorResponse (needs to be explicit).
  • Error status codes. The release notes don't document how ErrorResponse maps to HTTP codes. Be explicit about the status in the constructor if it is a parameter, and assert it in tests; otherwise every error may return 200.
  • Message localization. There is no mention of lang integration; if you need translated message fields, resolve them with __() before passing into the response.
  • Don't mix conventions mid-refactor. Transitioning half a project to these classes produces an inconsistent API for clients. Either ship the change behind a version bump (/api/v2) or convert all endpoints in one PR.
  • Debugging unexpected envelopes. dump($response->json()) or dd($response->toResponse(request())->getContent()) will show the exact shape. If a test fails with a missing key, it is usually because the wrong response class was chosen (e.g. SuccessResponse where CollectionResponse was intended).
  • First-release risk. v1.0.0 is the very first stable tag; the public surface (constructor signatures especially) may shift in 1.x minors. Pin the version in composer.json ("mahmoud-almalah/laravel-api-helpers": "^1.0") and watch the changelog before upgrading in production.
  • Extension points to remember: the ResponseInterface and the underlying service class are the intended hooks. Prefer them over reflection or overriding vendor code when you need custom behavior.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
uni-method/symfony-lib
tacticmedia/scim-server-bundle
neika-ai/symfony-bundle
mattleads/agent-publishing-bundle
glavweb/framework-bundle
glavweb/extra-bundle
glavweb/api-bundle
glavweb/admin-bundle
adachsoft/api-version-bundle
elsayed85/laravel-api-exceptions
ouhssini/laravel-demo-mode
daworks/ncloud-outbound-mailer-driver
gp247/cms
ignibyte/aic-gates
nexa-merchant/blog
novasa/laravel-language-center
opencage/geocode
adolfoholzer/parameters
livenetworks/ln-starter
cgv/localized-resource