adithwidhiantara/laravel-response-formatter

Simple JSON response formatter for Laravel

Installs: 4

Dependents: 0

Suggesters: 0

Security: 0

Stars: 0

Watchers: 0

Forks: 0

Open Issues: 0

pkg:composer/adithwidhiantara/laravel-response-formatter

1.0.0 2025-08-17 07:11 UTC

This package is auto-updated.

Last update: 2025-12-17 07:57:18 UTC


README

Package sederhana untuk memformat response JSON di Laravel dengan struktur yang konsisten.

Instalasi

Tambahkan package ke project Laravel kamu:

composer require adithwidhiantara/laravel-response-formatter

Jika belum rilis ke Packagist, gunakan repository lokal atau VCS (GitHub/GitLab) sesuai kebutuhan.

Cara Menggunakan

Import class ResponseFormatter:

use Adithwidhiantara\LaravelResponseFormatter\ResponseFormatter;

Success Response

return ResponseFormatter::success(
    data: ['id' => 1, 'name' => 'John Doe'],
    message: 'Data retrieved successfully',
    status: 'success',
    code: \Symfony\Component\HttpFoundation\Response::HTTP_OK
);

Output JSON:

{
  "status": "success",
  "message": "Data retrieved successfully",
  "data": {
    "id": 1,
    "name": "John Doe"
  }
}

Error Response

return ResponseFormatter::error(
    data: null,
    message: 'User not found',
    status: 'error',
    code: \Symfony\Component\HttpFoundation\Response::HTTP_NOT_FOUND
);

Output JSON:

{
  "status": "error",
  "message": "User not found",
  "data": null
}

Contoh Penggunaan di Controller

use App\Http\Controllers\Controller;
use Adithwidhiantara\LaravelResponseFormatter\ResponseFormatter;
use App\Models\User;
use Symfony\Component\HttpFoundation\Response;

class UserController extends Controller
{
    public function show($id)
    {
        $user = User::find($id);

        if (!$user) {
            return ResponseFormatter::error(
                message: 'User not found',
                code: Response::HTTP_NOT_FOUND
            );
        }

        return ResponseFormatter::success(
            data: $user,
            message: 'User retrieved successfully'
        );
    }
}

License

MIT License