Laravel Laresponse
Trait Laravel untuk standarisasi response JSON dengan format konsisten dan dukungan pagination
Versi: 0.1.0
Instalasi
Install via Composer:
composer require bpmlib/laravel-laresponseGunakan trait di Controller:
<?php
namespace App\Http\Controllers;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
class UserController extends Controller
{
use JsonResponseTrait;
public function index()
{
$users = User::all();
return $this->returnJson($users);
}
}Requirements
Library ini memerlukan:
PHP Version:
PHP ^8.1Required PHP Extensions:
ext-jsonComposer Dependencies:
| Package | Version | Description |
|---|---|---|
illuminate/support | ^10.0||^11.0||^12.0 | Laravel support package |
illuminate/http | ^10.0||^11.0||^12.0 | HTTP handling |
illuminate/pagination | ^10.0||^11.0||^12.0 | Pagination support |
illuminate/database | ^10.0||^11.0||^12.0 | Database query builder |
Framework Requirements:
| Framework | Version |
|---|---|
| Laravel | ^10.0 || ^11.0 || ^12.0 |
Quick Start
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
class UserController extends Controller
{
use JsonResponseTrait;
public function index()
{
$users = User::all();
return $this->returnJson(
content: $users,
code: 200
);
}
}Output:
{
"message": "Sukses",
"content": [...],
"success": true
}Core Concepts
Contains:
- Response Structure Standar
- Pesan Default Otomatis
- Success Flag Otomatis
- Mapper Function
- Appends Behavior
- Validation Errors
- Struktur Response Konsisten 1:1
Response Structure Standar
Semua response JSON mengikuti struktur yang konsisten:
[
'message' => string, // Pesan response
'content' => mixed, // Data utama
'success' => bool, // Status sukses (otomatis dari HTTP code)
'validation' => array // (opsional) Error validasi untuk code 422
]Implications:
<?php
// Frontend dapat selalu mengharapkan struktur yang sama
const response = await fetch('/api/users');
const data = await response.json();
// Selalu ada: message, content, success
console.log(data.message); // "Sukses"
console.log(data.content); // [...]
console.log(data.success); // truePesan Default Otomatis
Library menyediakan pesan default untuk HTTP status code umum:
| Code | Pesan Default |
|---|---|
200 | "Sukses" |
201 | "Sukses dibuat" |
400 | "Pastikan format request yang Anda kirimkan sesuai" |
401 | "Anda belum login" |
403 | "Anda tidak mempunyai akses untuk ini" |
404 | "Data yang anda cari tidak ada" |
422 | "Form yang anda kirimkan ada yang tidak valid" |
500 | "Terjadi kesalahan di server" |
503 | "Server sedang sibuk" |
How it works:
- Jika parameter
$messagekosong, library akan menggunakan pesan default sesuai$code - Jika
$codetidak ada di dictionary, pesan default adalah "Hai 😄" - Anda dapat override dengan memberikan parameter
$messagecustom
Success Flag Otomatis
Field success dihitung otomatis berdasarkan HTTP status code:
'success' => $code >= 200 && $code <= 299Key points:
- Status 2xx →
success: true - Status selain 2xx →
success: false - Tidak perlu set manual
Mapper Function
Semua method response mendukung parameter $mapper untuk transformasi data:
How it works:
- Jika
$contentadalahCollection→ menggunakanmap() - Jika
$contentadalah array list → menggunakanarray_map() - Jika
$contentadalah array associative → memanggil mapper langsung - Jika
$contentadalah object → memanggil mapper langsung
Contoh:
<?php
$users = User::all();
return $this->returnJson(
content: $users,
mapper: fn($user) => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
]
);Appends Behavior
Parameter $appends memungkinkan menambahkan field custom ke response:
Important rules:
- Appends tidak dapat menimpa key bawaan (
message,content,success,validation) - Menggunakan
array_diff_key()untuk mencegah override - Berguna untuk menambahkan metadata tambahan
Contoh:
<?php
return $this->returnJson(
content: $data,
appends: [
'timestamp' => now(),
'version' => '1.0',
'message' => 'This will be ignored' // Tidak akan menimpa message bawaan
]
);Validation Errors
Field validation hanya ditambahkan jika:
- Parameter
$validationErrorstidak kosong - HTTP status code adalah
422
Automatic normalization:
- Menerima
arrayatauMessageBag - Otomatis convert
MessageBagke array
Struktur Response Konsisten 1:1
Semua method pagination (returnPaginateJson, returnCursorPaginateJson, returnSimplePaginateJson) menghasilkan struktur response dengan key yang sama, hanya nilainya yang berbeda:
[
'message' => string,
'content' => array,
'success' => bool,
// Pagination metadata (selalu ada)
'max_page' => int|null,
'current_page' => int|null,
'per_page' => int,
'total' => int|null,
'has_more' => bool,
'next_cursor' => string|null,
'previous_cursor' => string|null,
]How it works:
- Semua 7 key pagination metadata selalu ada di response
- Key yang tidak relevan diisi dengan
null - Ini memudahkan frontend karena structure selalu sama
Contoh:
| Method | max_page | current_page | total | next_cursor | previous_cursor |
|---|---|---|---|---|---|
returnPaginateJson() | 10 | 1 | 145 | null | null |
returnCursorPaginateJson() | null | null | null | "eyJ..." | null |
returnSimplePaginateJson() | null | 1 | null | null | null |
Key benefits:
- Frontend tidak perlu conditional logic untuk handle struktur berbeda
- Type safety di TypeScript/JavaScript
- Konsisten dengan standard pagination REST API
Catatan: Method returnJson() tidak memiliki pagination metadata sama sekali (hanya message, content, success).
API Reference
Traits
JsonResponseTrait
Trait untuk standarisasi JSON response di Laravel Controller.
Namespace: Bpmlib\Laresponse\Traits\JsonResponseTrait
Usage:
<?php
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
class MyController extends Controller
{
use JsonResponseTrait;
}Methods
Contains:
- returnJson()
- returnPaginateJson()
- returnCursorPaginateJson()
- returnSimplePaginateJson()
- returnAdaptive()
returnJson()
protected function returnJson(
mixed $content = [],
int $code = 200,
string $message = '',
array|MessageBag $validationErrors = [],
?callable $mapper = null,
array $appends = [],
array $returnHeaders = [],
int $returnOptions = JSON_THROW_ON_ERROR
): JsonResponseMenghasilkan response JSON dengan format standar aplikasi.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$content | mixed | [] | Data utama yang akan dikembalikan |
$code | int | 200 | HTTP status code response |
$message | string | '' | Pesan custom. Jika kosong, otomatis berdasarkan status code |
$validationErrors | array|MessageBag | [] | Error validasi (hanya untuk status 422) |
$mapper | ?callable | null | Callback untuk transformasi data content |
$appends | array | [] | Data tambahan yang digabungkan ke response |
$returnHeaders | array | [] | Header HTTP tambahan |
$returnOptions | int | JSON_THROW_ON_ERROR | Opsi encoding JSON |
Returns: JsonResponse dengan struktur:
[
'message' => string,
'content' => mixed,
'success' => bool,
'validation' => array // hanya jika code 422 dan ada validationErrors
]Contoh:
<?php
// Basic usage
return $this->returnJson(
content: ['user' => $user],
code: 200
);
// With validation errors
return $this->returnJson(
content: [],
code: 422,
validationErrors: $validator->errors()
);
// With mapper
return $this->returnJson(
content: $users,
mapper: fn($user) => [
'id' => $user->id,
'name' => $user->name
]
);returnPaginateJson()
protected function returnPaginateJson(
LengthAwarePaginator $content,
int $code = 200,
string $message = 'Success',
?callable $mapper = null,
array $appends = [],
array $returnHeaders = [],
int $returnOptions = JSON_THROW_ON_ERROR
): JsonResponseResponse JSON untuk LengthAwarePaginator dengan informasi paginasi lengkap.
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$content | LengthAwarePaginator | - | Data paginated dari Laravel |
$code | int | 200 | HTTP status code |
$message | string | 'Success' | Pesan response |
$mapper | ?callable | null | Callback untuk transformasi items |
$appends | array | [] | Data tambahan |
$returnHeaders | array | [] | Header HTTP tambahan |
$returnOptions | int | JSON_THROW_ON_ERROR | Opsi encoding JSON |
Returns: JsonResponse dengan struktur:
[
'message' => string,
'content' => array, // Items dari paginator
'success' => bool,
'max_page' => int, // Total halaman
'current_page' => int, // Halaman aktif
'per_page' => int, // Jumlah item per halaman
'total' => int, // Total items
'has_more' => bool, // Apakah ada halaman berikutnya
'next_cursor' => null, // Tidak digunakan (untuk konsistensi)
'previous_cursor' => null // Tidak digunakan (untuk konsistensi)
]Contoh:
<?php
$users = User::paginate(15);
return $this->returnPaginateJson(
content: $users,
mapper: fn($user) => [
'id' => $user->id,
'name' => $user->name
]
);returnCursorPaginateJson()
protected function returnCursorPaginateJson(
CursorPaginator $content,
int $code = 200,
string $message = 'Success',
?callable $mapper = null,
array $appends = [],
array $returnHeaders = [],
int $returnOptions = JSON_THROW_ON_ERROR
): JsonResponseResponse JSON untuk CursorPaginator (infinite scroll).
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$content | CursorPaginator | - | Data cursor paginated dari Laravel |
$code | int | 200 | HTTP status code |
$message | string | 'Success' | Pesan response |
$mapper | ?callable | null | Callback untuk transformasi items |
$appends | array | [] | Data tambahan |
$returnHeaders | array | [] | Header HTTP tambahan |
$returnOptions | int | JSON_THROW_ON_ERROR | Opsi encoding JSON |
Returns: JsonResponse dengan struktur:
[
'message' => string,
'content' => array,
'success' => bool,
'per_page' => int,
'has_more' => bool,
'next_cursor' => ?string, // Encoded cursor untuk halaman berikutnya
'previous_cursor' => ?string, // Encoded cursor untuk halaman sebelumnya
'current_page' => null, // Tidak digunakan (untuk konsistensi)
'max_page' => null, // Tidak digunakan (untuk konsistensi)
'total' => null // Tidak digunakan (untuk konsistensi)
]Contoh:
<?php
$posts = Post::cursorPaginate(20);
return $this->returnCursorPaginateJson(
content: $posts,
mapper: fn($post) => [
'id' => $post->id,
'title' => $post->title,
'created_at' => $post->created_at->toISOString()
]
);returnSimplePaginateJson()
protected function returnSimplePaginateJson(
Paginator $content,
int $code = 200,
string $message = 'Success',
?callable $mapper = null,
array $appends = [],
array $returnHeaders = [],
int $returnOptions = JSON_THROW_ON_ERROR
): JsonResponseResponse JSON untuk SimplePaginator (pagination tanpa total count).
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$content | Paginator | - | Data simple paginated dari Laravel |
$code | int | 200 | HTTP status code |
$message | string | 'Success' | Pesan response |
$mapper | ?callable | null | Callback untuk transformasi items |
$appends | array | [] | Data tambahan |
$returnHeaders | array | [] | Header HTTP tambahan |
$returnOptions | int | JSON_THROW_ON_ERROR | Opsi encoding JSON |
Returns: JsonResponse dengan struktur:
[
'message' => string,
'content' => array,
'success' => bool,
'per_page' => int,
'current_page' => int,
'has_more' => bool,
'total' => null, // Tidak digunakan (untuk konsistensi)
'max_page' => null, // Tidak digunakan (untuk konsistensi)
'next_cursor' => null, // Tidak digunakan (untuk konsistensi)
'previous_cursor' => null // Tidak digunakan (untuk konsistensi)
]Contoh:
<?php
$products = Product::simplePaginate(10);
return $this->returnSimplePaginateJson(
content: $products,
mapper: fn($product) => [
'id' => $product->id,
'name' => $product->name,
'price' => $product->price
]
);returnAdaptive()
protected function returnAdaptive(
Collection|LengthAwarePaginator|CursorPaginator|Paginator|array $content,
string $message = '',
int $code = 200,
?callable $mapper = null,
array $appends = [],
array $returnHeaders = [],
int $returnOptions = JSON_THROW_ON_ERROR
): JsonResponseAdaptive response yang otomatis memilih method sesuai tipe data.
How it works:
- Jika
LengthAwarePaginator→ memanggilreturnPaginateJson() - Jika
CursorPaginator→ memanggilreturnCursorPaginateJson() - Jika
Paginator→ memanggilreturnSimplePaginateJson() - Selain itu → memanggil
returnJson()
Parameters
| Name | Type | Default | Description |
|---|---|---|---|
$content | Collection|LengthAwarePaginator|CursorPaginator|Paginator|array | - | Data dalam format apapun |
$message | string | '' | Pesan response |
$code | int | 200 | HTTP status code |
$mapper | ?callable | null | Callback untuk transformasi |
$appends | array | [] | Data tambahan |
$returnHeaders | array | [] | Header HTTP tambahan |
$returnOptions | int | JSON_THROW_ON_ERROR | Opsi encoding JSON |
Returns: JsonResponse dengan struktur sesuai tipe data input
Contoh:
<?php
public function index(Request $request)
{
// Adaptive: otomatis detect pagination atau tidak
$users = $request->has('paginate')
? User::paginate(15)
: User::all();
return $this->returnAdaptive(
content: $users,
mapper: fn($user) => [
'id' => $user->id,
'name' => $user->name
]
);
}Examples
Contains:
- 1. Penggunaan Dasar
- 2. Response dengan Validasi Error
- 3. Response dengan Mapper
- 4. Response Paginated Data (LengthAware)
- 5. Response Cursor Pagination (Infinite Scroll)
- 6. Response Simple Pagination
- 7. Response Adaptive (Auto-detect)
- 8. Custom Message dan Status Code
- 9. Response dengan Appends
- 10. Response dengan Custom Headers
1. Penggunaan Dasar
Contoh paling sederhana menggunakan returnJson untuk mengembalikan data.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
class UserController extends Controller
{
use JsonResponseTrait;
public function show(int $id)
{
$user = User::findOrFail($id);
return $this->returnJson(
content: $user,
code: 200
);
}
}Output:
{
"message": "Sukses",
"content": {
"id": 1,
"name": "John Doe",
"email": "john@example.com"
},
"success": true
}2. Response dengan Validasi Error
Mengembalikan error validasi dengan status 422.
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StoreUserRequest;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
use Illuminate\Support\Facades\Validator;
class UserController extends Controller
{
use JsonResponseTrait;
public function store(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|email|unique:users',
]);
if ($validator->fails()) {
return $this->returnJson(
content: [],
code: 422,
validationErrors: $validator->errors()
);
}
$user = User::create($validator->validated());
return $this->returnJson(
content: $user,
code: 201
);
}
}Output (jika validasi gagal):
{
"message": "Form yang anda kirimkan ada yang tidak valid",
"content": [],
"success": false,
"validation": {
"email": ["The email field is required."],
"name": ["The name field is required."]
}
}3. Response dengan Mapper
Transformasi data sebelum dikembalikan menggunakan mapper function.
<?php
namespace App\Http\Controllers;
use App\Models\User;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
class UserController extends Controller
{
use JsonResponseTrait;
public function index()
{
$users = User::with('profile')->get();
return $this->returnJson(
content: $users,
mapper: fn($user) => [
'id' => $user->id,
'name' => $user->name,
'email' => $user->email,
'avatar' => $user->profile?->avatar_url,
'joined_at' => $user->created_at->format('Y-m-d'),
]
);
}
}Output:
{
"message": "Sukses",
"content": [
{
"id": 1,
"name": "John Doe",
"email": "john@example.com",
"avatar": "https://example.com/avatar.jpg",
"joined_at": "2024-01-15"
}
],
"success": true
}4. Response Paginated Data (LengthAware)
Menggunakan LengthAwarePaginator untuk pagination dengan total count.
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
class PostController extends Controller
{
use JsonResponseTrait;
public function index()
{
$posts = Post::with('author')
->latest()
->paginate(15);
return $this->returnPaginateJson(
content: $posts,
mapper: fn($post) => [
'id' => $post->id,
'title' => $post->title,
'excerpt' => substr($post->content, 0, 100),
'author' => $post->author->name,
'published_at' => $post->published_at->toISOString(),
]
);
}
}Output:
{
"message": "Success",
"content": [...],
"success": true,
"max_page": 10,
"current_page": 1,
"per_page": 15,
"total": 145,
"has_more": true,
"next_cursor": null,
"previous_cursor": null
}Key Takeaways:
max_pagedantotaltersedia untuk navigasi halamannext_cursordanprevious_cursorselalunull(tidak digunakan untuk LengthAware)
5. Response Cursor Pagination (Infinite Scroll)
Menggunakan CursorPaginator untuk infinite scroll tanpa total count.
<?php
namespace App\Http\Controllers;
use App\Models\Tweet;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
class TweetController extends Controller
{
use JsonResponseTrait;
public function timeline()
{
$tweets = Tweet::with('user')
->orderBy('created_at', 'desc')
->cursorPaginate(20);
return $this->returnCursorPaginateJson(
content: $tweets,
mapper: fn($tweet) => [
'id' => $tweet->id,
'text' => $tweet->text,
'user' => [
'id' => $tweet->user->id,
'name' => $tweet->user->name,
'username' => $tweet->user->username,
],
'created_at' => $tweet->created_at->toISOString(),
]
);
}
}Output:
{
"message": "Success",
"content": [...],
"success": true,
"per_page": 20,
"has_more": true,
"next_cursor": "eyJjcmVhdGVkX2F0IjoiMjAyNC0wMS0xNSAxMjozMDowMCIsIl9wb2ludHNUb05leHRJdGVtcyI6dHJ1ZX0",
"previous_cursor": null,
"current_page": null,
"max_page": null,
"total": null
}Key Takeaways:
next_cursordigunakan untuk fetch halaman berikutnyaprevious_cursoruntuk navigasi mundur (jika ada)total,max_page,current_pageselalunull
6. Response Simple Pagination
Menggunakan SimplePaginator untuk pagination ringan tanpa total count.
<?php
namespace App\Http\Controllers;
use App\Models\Product;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
class ProductController extends Controller
{
use JsonResponseTrait;
public function catalog()
{
$products = Product::where('is_active', true)
->simplePaginate(12);
return $this->returnSimplePaginateJson(
content: $products,
mapper: fn($product) => [
'id' => $product->id,
'name' => $product->name,
'price' => $product->price,
'image' => $product->thumbnail_url,
]
);
}
}Output:
{
"message": "Success",
"content": [...],
"success": true,
"per_page": 12,
"current_page": 1,
"has_more": true,
"total": null,
"max_page": null,
"next_cursor": null,
"previous_cursor": null
}Key Takeaways:
- Lebih cepat dari LengthAware karena tidak query total count
- Cocok untuk list produk, artikel, dll yang tidak butuh total pages
7. Response Adaptive (Auto-detect)
Menggunakan returnAdaptive yang otomatis detect tipe data.
<?php
namespace App\Http\Controllers;
use App\Models\Article;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
use Illuminate\Http\Request;
class ArticleController extends Controller
{
use JsonResponseTrait;
public function index(Request $request)
{
// Query builder bisa return Collection atau Paginator
$query = Article::query();
$articles = $request->boolean('paginate')
? $query->paginate(10)
: $query->get();
// Adaptive otomatis pilih method yang sesuai
return $this->returnAdaptive(
content: $articles,
mapper: fn($article) => [
'id' => $article->id,
'title' => $article->title,
'slug' => $article->slug,
]
);
}
}Key Takeaways:
- Berguna untuk endpoint yang bisa return paginated atau non-paginated
- Tidak perlu conditional logic untuk pilih method
- Output structure mengikuti tipe data input
8. Custom Message dan Status Code
Menggunakan custom message dan berbagai status code.
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
class OrderController extends Controller
{
use JsonResponseTrait;
public function cancel(int $id)
{
$order = Order::findOrFail($id);
if ($order->status === 'shipped') {
return $this->returnJson(
content: [],
code: 400,
message: 'Pesanan yang sudah dikirim tidak dapat dibatalkan'
);
}
if ($order->user_id !== auth()->id()) {
return $this->returnJson(
content: [],
code: 403,
message: 'Anda tidak memiliki akses untuk membatalkan pesanan ini'
);
}
$order->update(['status' => 'cancelled']);
return $this->returnJson(
content: $order,
code: 200,
message: 'Pesanan berhasil dibatalkan'
);
}
}Output (sukses):
{
"message": "Pesanan berhasil dibatalkan",
"content": {...},
"success": true
}Output (error - shipped):
{
"message": "Pesanan yang sudah dikirim tidak dapat dibatalkan",
"content": [],
"success": false
}9. Response dengan Appends
Menambahkan metadata tambahan ke response.
<?php
namespace App\Http\Controllers;
use App\Models\Dashboard;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
class DashboardController extends Controller
{
use JsonResponseTrait;
public function stats()
{
$stats = [
'total_users' => User::count(),
'total_orders' => Order::count(),
'total_revenue' => Order::sum('total'),
];
return $this->returnJson(
content: $stats,
appends: [
'timestamp' => now()->toISOString(),
'timezone' => config('app.timezone'),
'version' => config('app.version'),
]
);
}
}Output:
{
"message": "Sukses",
"content": {
"total_users": 1250,
"total_orders": 3420,
"total_revenue": 125000000
},
"success": true,
"timestamp": "2024-12-21T10:30:00.000000Z",
"timezone": "Asia/Jakarta",
"version": "1.0.0"
}Key Takeaways:
- Appends tidak dapat override key bawaan (
message,content,success) - Berguna untuk menambahkan metadata, timestamp, version info, dll
10. Response dengan Custom Headers
Menambahkan custom HTTP headers ke response.
<?php
namespace App\Http\Controllers;
use App\Models\Report;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
class ReportController extends Controller
{
use JsonResponseTrait;
public function generate()
{
$report = Report::generate();
return $this->returnJson(
content: $report,
returnHeaders: [
'X-Report-ID' => $report->id,
'X-Generated-At' => now()->toRfc7231String(),
'Cache-Control' => 'no-cache, no-store, must-revalidate',
]
);
}
}Response Headers:
HTTP/1.1 200 OK
Content-Type: application/json
X-Report-ID: 12345
X-Generated-At: Sat, 21 Dec 2024 10:30:00 GMT
Cache-Control: no-cache, no-store, must-revalidateKey Takeaways:
- Berguna untuk custom caching, CORS, rate limiting, dll
- Headers tidak terlihat di response body, hanya di HTTP headers
Laravel Integration
Installation
Library ini tidak memerlukan service provider karena hanya berisi trait.
Usage in Controllers
Gunakan trait di base controller atau individual controller:
<?php
namespace App\Http\Controllers;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
class Controller extends BaseController
{
use AuthorizesRequests, ValidatesRequests, JsonResponseTrait;
}Setelah itu, semua controller yang extends dari Controller otomatis memiliki akses ke method response JSON.
Usage in API Resources
Anda juga dapat menggunakan trait ini di API Resource:
<?php
namespace App\Http\Resources;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
use Illuminate\Http\Resources\Json\ResourceCollection;
class UserCollection extends ResourceCollection
{
use JsonResponseTrait;
public function toArray($request)
{
return $this->returnPaginateJson(
content: $this->collection,
mapper: fn($user) => [
'id' => $user->id,
'name' => $user->name,
]
);
}
}Integration dengan Form Requests
Combine dengan Laravel Form Requests:
<?php
namespace App\Http\Controllers;
use App\Http\Requests\StorePostRequest;
use App\Models\Post;
use Bpmlib\Laresponse\Traits\JsonResponseTrait;
class PostController extends Controller
{
use JsonResponseTrait;
public function store(StorePostRequest $request)
{
// Validasi sudah dilakukan oleh Form Request
$post = Post::create($request->validated());
return $this->returnJson(
content: $post,
code: 201,
message: 'Post berhasil dibuat'
);
}
}