Answer the question
In order to leave comments, you need to log in
How to properly work with JsonResource in Laravel?
Colleagues, I ask for your help! ¯\(ツ)/¯
I am writing a backend REST-api component for one project.
I have an api-route domain.ru/api/offices, which should return a list of offices and employees (employees) working in each office.
I have created an OfficeResource and an OfficeCollection to get one and many offices respectively, also give the code of EmployeeResource
OfficeResource
return [
"id" => $this->id,
"code" => $this->code,
"address" => $this->address,
"employees" => new EmployeeCollection($this->employees),
"created_at" => $this->created_at
];
return [
"id" => $this->id,
"name" => $this->name,
"office" => $this->office
];
Route::get('offices', function (Request $request) {
$office_collection = new OfficeCollection(Office::all());
foreach ($office_collection as $office) {
foreach ($office->employees as $employee) {
unset($employee['id_office']);
}
}
return response()->json([
"status" => true,
"response" => $office_collection,
], 200);
});
{
"status": true,
"response": [
{
"id": 1,
"code": "e4bK4A0UIE",
"address": "Ленина, 10",
"employees": [
{
"id": 7,
"name": "Elyssa Grady",
"office": null
},
{
"id": 8,
"name": "Manuel Schimmel",
"office": null
},
{
"id": 10,
"name": "Thelma Vandervort",
"office": null
}
],
"created_at": "2021-04-11T12:50:56.000000Z"
},
}
Route::get('employees', function (Request $request) {
return response()->json([
"status" => true,
"response" => new EmployeeCollection(Employee::all())
], 200);
});
{
"status": true,
"response": [
{
"id": 1,
"name": "Schuyler Kilback",
"office": {
"id": 4,
"code": "8ZJzJpdNe!",
"address": "ySm7XUUIgpkWYfuHoaFG",
"created_at": "2021-04-11T12:50:56.000000Z"
}
},
]
}
Answer the question
In order to leave comments, you need to log in
The whenLoaded
method may be used to conditionally load a relationship. In order to avoid unnecessarily loading relationships, this method accepts the name of the relationship instead of the relationship itself:
use App\Http\Resources\PostResource;
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'email' => $this->email,
'posts' => PostResource::collection($this->whenLoaded('posts')),
'created_at' => $this->created_at,
'updated_at' => $this->updated_at,
];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question