PHPackages                             xetreon/jsonresponse - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Logging &amp; Monitoring](/categories/logging)
4. /
5. xetreon/jsonresponse

ActiveLibrary[Logging &amp; Monitoring](/categories/logging)

xetreon/jsonresponse
====================

A simple, lightweight Laravel package for standardized JSON API responses, validation, and logging.

0.0.2.1(9mo ago)0344↓92.9%MITPHPPHP ^8.1

Since Sep 14Pushed 8mo agoCompare

[ Source](https://github.com/xetreon/json-response)[ Packagist](https://packagist.org/packages/xetreon/jsonresponse)[ RSS](/packages/xetreon-jsonresponse/feed)WikiDiscussions master Synced today

READMEChangelog (2)DependenciesVersions (6)Used By (0)

Xetreon JSON Response
=====================

[](#xetreon-json-response)

A lightweight Laravel package for **standardized JSON API responses**, validation, and error logging.
Perfect for building **clean, consistent REST APIs** without repeating boilerplate code.

---

☕ Support Me
------------

[](#-support-me)

If you find this package helpful, consider supporting my work:

[![Buy Me a Coffee](https://camo.githubusercontent.com/121ab1e6f18085acf960ea6dc2d1a763504de40c6784b73614afe485798749de/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f4275792532304d6525323061253230436f666665652d2532334646444430303f7374796c653d666f722d7468652d6261646765266c6f676f3d6275792d6d652d612d636f66666565266c6f676f436f6c6f723d626c61636b)](https://buymeacoffee.com/xetreon)
------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

[](#)

🚀 Features
----------

[](#-features)

- ✅ **Consistent JSON responses** (`success`, `error`, `validationError`)
- ✅ **Built-in validation helpers** with structured error output
- ✅ **Automatic error logging** with unique `trace_id` for easier debugging
- ✅ **Extensible BaseController** and **BaseException**
- ✅ **Publishable traits and base classes** for full customization
- ✅ **Configuration publishing** for easy overrides

---

📦 Installation
--------------

[](#-installation)

**Require the package via Composer:**

```
composer require xetreon/jsonresponse
```

**Publish the config file to customize defaults:**

```
php artisan vendor:publish --tag=config

```

🧩 Usage Example
---------------

[](#-usage-example)

Here’s how you can use `Xetreon\JsonResponse\Controllers\BaseController` in your controllers.

```
use Xetreon\JsonResponse\Controllers\BaseController;
use Illuminate\Http\Request;
use App\Models\User;

class UserController extends BaseController
{
    public function index(Request $request)
    {
        $users = User::query();

        // fetchFromQuery automatically applies:
        // - status filtering (status[])
        // - sorting (sort_by & sort_order)
        // - pagination (per_page)
        return $this->fetchFromQuery($users, $request->all());
    }

    public function show($id)
    {
        return $this->fetchById(User::query(), $id, 'User not found');
    }
}
```

#### 📥 Sample Request JSON

[](#-sample-request-json)

```
{
  "status": ["active", "pending"],  // Filter results by status (uses whereIn)
  "sort_by": "created_at",          // Sort field
  "sort_order": "DESC",             // Sorting direction (ASC or DESC)
  "per_page": 15                    // Pagination size
}
```

#### 🖥 Example cURL Request

[](#-example-curl-request)

```
curl --location 'https://your-app.test/api/users' \
--header 'Accept: application/json' \
--header 'Content-Type: application/json' \
--data '{
    "status": ["active", "pending"],
    "sort_by": "created_at",
    "sort_order": "DESC",
    "per_page": 15
}'
```

⚡ Direct Usage of Response Methods
----------------------------------

[](#-direct-usage-of-response-methods)

You can use the built-in response helper methods in your controllers for quick and consistent JSON responses.

#### ✅ Success Response

[](#-success-response)

```
return $this->success(true, ['foo' => 'bar'], 'Operation successful');
```

```
return $this->error(false, [], 'Something went wrong', 500);
```

🛡️ Validation Helper
--------------------

[](#️-validation-helper)

Use the built-in `validate()` method for consistent request validation and error responses.

#### Example Usage

[](#example-usage)

```
$result = $this->validate($request->all(), [
    'email' => 'required|email',
    'password' => 'required|min:8',
]);

if (!$result['result']) {
    return $this->validationError($result);
}
```

🛠 Publishing Base Classes and Traits
------------------------------------

[](#-publishing-base-classes-and-traits)

You can publish the `BaseController` and `BaseException` into your application for customization.

#### 🎛 Publish Classes

[](#-publish-classes)

```
php artisan vendor:publish --tag=classes
```

#### 🎛 Publishing Traits

[](#-publishing-traits)

```
php artisan vendor:publish --tag=xetreon-jsonresponse-traits
```

📝 Using the LoggerTrait
-----------------------

[](#-using-the-loggertrait)

The `LoggerTrait` provides an easy way to log **info**, **warning**, and **error** messages with consistent formatting and automatic file/line code references.

---

### 1️⃣ Importing &amp; Using the Trait

[](#1️⃣-importing--using-the-trait)

```
use Xetreon\JsonResponse\Traits\LoggerTrait;

class OrderService
{
    use LoggerTrait;

    public function processOrder($order)
    {
        // Log an informational message
        $this->createLog('Starting order processing', ['order_id' => $order->id]);

        try {
            // Your order processing logic...
        } catch (\Throwable $e) {
            // Log an error with context
            $this->createErrorLog('Order processing failed', [
                'order_id' => $order->id,
                'exception' => $e->getMessage()
            ]);
        }
    }
}
```

### 2️⃣ Available Methods

[](#2️⃣-available-methods)

MethodLevelParametersExample`createLog()`Info`string $message, array $context = [], int $trace = 1``$this->createLog('User created', ['id' => 1]);``createWarningLog()`Warning`string $message, array $context = [], int $trace = 1``$this->createWarningLog('User quota nearing limit');``createErrorLog()`Error`string $message, array $context = [], int $trace = 1``$this->createErrorLog('Critical failure', ['error' => $e->getMessage()]);`---

**Parameter Details:**

- **`$message`** → A short, human-readable message.
- **`$context`** → Additional data to log (automatically JSON-encoded).
- **`$trace`** → *(Optional)* Stack trace depth — `1` for current method, `2` for caller, etc.

---

### 3️⃣ Output Example (Log File)

[](#3️⃣-output-example-log-file)

When logging using `LoggerTrait`, you get standardized log entries:

```
[2025-09-14 15:30:12] local.INFO: APP_COMMON - Starting order processing {"order_id":123}
[2025-09-14 15:30:13] local.ERROR: APP_COMMON - Order processing failed {"order_id":123,"exception":"Insufficient stock"}

```

### 4️⃣ Customizing the Log Channel

[](#4️⃣-customizing-the-log-channel)

You can configure which channel `LoggerTrait` writes to by editing `config/xetreon-jsonresponse.php`:

```
'log_channel' => env('XETREON_JSON_LOG_CHANNEL', config('logging.default')),
```

Or overwrite via `.env`

```
XETREON_JSON_LOG_CHANNEL=stack

```

### 5️⃣ Using Class Codes

[](#5️⃣-using-class-codes)

You can map specific files to **short class codes** for more meaningful log identifiers.

### Example Configuration (`config/xetreon-jsonresponse.php`)

[](#example-configuration-configxetreon-jsonresponsephp)

```
'classcode' => [
    'app/Services/OrderService.php' => 'ORD',
    'app/Http/Controllers/UserController.php' => 'USR',
],
```

### ✅ Example Log Output

[](#-example-log-output)

```
[2025-09-14 15:30:12] local.INFO: ORD:123 - Starting order processing {"order_id":123}

```

Here you will get the controller code : line number in the log.

### ✅ Why Use LoggerTrait?

[](#-why-use-loggertrait)

- **Consistent:** Ensures the same log format across the entire application.
- **Traceable:** Automatically adds file name and line number to every log entry.
- **Configurable:** Lets you choose the log channel per environment.
- **Structured:** Always logs with JSON-encoded context for easy parsing and analysis.

⚠️ Exception Usage
------------------

[](#️-exception-usage)

You can throw a `BaseException` anywhere in your application code to return a standardized JSON error response.

#### 💻 Example

[](#-example)

```
use Xetreon\JsonResponse\Exceptions\BaseException;

throw new BaseException('Something went wrong', 500, ['context' => 'extra-data']);
```

#### 📤 Example JSON Response

[](#-example-json-response)

```
{
  "result": false,
  "data": {
    "context": "extra-data"
  },
  "message": "Something went wrong",
  "status_code": 500,
  "error": {
    "type": "BaseException",
    "file": "app/Services/OrderService.php",
    "line": 42,
    "time": "2025-09-14 16:00:00",
    "code": "APP_COMMON"
  }
}
```

#### ✅ Highlights

[](#-highlights)

- **`file` &amp; `line`** – Useful in local/dev environments *(hidden in production for security)*.
- **`code`** – Class code or module identifier for quick filtering in logs.
- **`time`** – Exact timestamp when the exception was thrown.

### ⚠️ Extending BaseException

[](#️-extending-baseexception)

You can create custom exceptions that extend `BaseException` for different error scenarios.

#### 💻 Example

[](#-example-1)

```
