Cách sử dụng CustomerResource, CustomerResource::collection để chuyển dữ liệu về dạn Json (ok)
Nhưng chú ý với v8x trở lên nó đã hỗ trợ sẵn sàng chuyển sang json rồi 😒
php artisan make:resource CustomerResourceC:\xampp\htdocs\api\app\Http\Resources\CustomerResource.php
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class CustomerResource extends JsonResource {
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array|\Illuminate\Contracts\Support\Arrayable|\JsonSerializable
*/
public function toArray($request) {
return parent::toArray($request);
}
}Áp dụng C:\xampp\htdocs\api\app\Http\Controllers\CustomerController.php
<?php
namespace App\Http\Controllers;
use App\Models\Customer;
use Illuminate\Http\Request;
use App\Http\Resources\CustomerResource;
class CustomerController extends Controller {
/**
* Display a listing of the resource.
*
* @return \Illuminate\Http\Response
*/
public function index() {
return Customer::all();
}
/**
* Show the form for creating a new resource.
*
* @return \Illuminate\Http\Response
*/
public function create() {
//
}
/**
* Store a newly created resource in storage.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
public function store(Request $request) {
//
}
/**
* Display the specified resource.
*
* @param \App\Models\Customer $customer
* @return \Illuminate\Http\Response
*/
public function show(Customer $customer) {
return new CustomerResource::find($customer);
}
/**
* Show the form for editing the specified resource.
*
* @param \App\Models\Customer $customer
* @return \Illuminate\Http\Response
*/
public function edit(Customer $customer) {
//
}
/**
* Update the specified resource in storage.
*
* @param \Illuminate\Http\Request $request
* @param \App\Models\Customer $customer
* @return \Illuminate\Http\Response
*/
public function update(Request $request, Customer $customer) {
//
}
/**
* Remove the specified resource from storage.
*
* @param \App\Models\Customer $customer
* @return \Illuminate\Http\Response
*/
public function destroy(Customer $customer) {
//
}
}Phiên bản mới chúng ra chỉ cần
Kết quả khác nhau ở key nhau :)


Chú ý: 😒😒😒😒 ngoài ra chúng ta có thể tùy biến giá trị trả về của C:\xampp\htdocs\api\app\Http\Resources\CustomerResource.php
Kết quả là:

Một chú ý quan trọng nữa là: CustomerResource trả về api chỉ khi có dạng tham số giống với hình

Còn khi không có tham số thì chúng ta sử dụng như sau

Kết quả 😁
Hoặc tạo hẳn một collection riêng có một chút khác biệt hãy so sánh
C:\xampp\htdocs\api\app\Http\Resources\CustomerCollection.php
C:\xampp\htdocs\api\app\Http\Controllers\CustomerController.php

Chú ý sử dung cách cuối này dữ liệu gọn gàng hơn nó tổng hợp thành meta, linh giống hình thuận tiện cho phân trang sau này :)

Last updated
Was this helpful?