https://github.com/eightyfive/laravel-normalizr
Normalizr Laravel Eloquent API Resources
https://github.com/eightyfive/laravel-normalizr
Last synced: 6 months ago
JSON representation
Normalizr Laravel Eloquent API Resources
- Host: GitHub
- URL: https://github.com/eightyfive/laravel-normalizr
- Owner: eightyfive
- License: mit
- Created: 2020-04-28T02:56:33.000Z (about 6 years ago)
- Default Branch: master
- Last Pushed: 2020-06-19T11:33:53.000Z (almost 6 years ago)
- Last Synced: 2025-01-23T03:41:23.309Z (over 1 year ago)
- Language: PHP
- Size: 19.5 KB
- Stars: 0
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# laravel-normalizr
Normalizr Laravel Eloquent API Resources
## Install
```
composer require eyf/laravel-normalizr
```
## Usage
```php
use Eyf\Normalizr\Http\Resources\JsonResource;
class User extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
// ...
'posts' => Post::collection($this->whenLoaded('posts')),
];
}
}
```
### Controller
Assuming [route model binding](https://laravel.com/docs/7.x/routing#route-model-binding).
```php
use App\Http\Resources\User as UserResource;
class UserController extends Controller
{
public function find(Request $request, User $user)
{
$user->loadMissing('posts');
return new UserResource($user);
}
}
```
### Response
```json
{
"data": {
"entities": {
"users": {
"1": {
"id": 1,
"name": "John",
"posts": [2, 3]
}
},
"posts": {
"2": {
"id": 2,
"title": "Post 2"
},
"3": {
"id": 3,
"title": "Post 3"
}
}
},
"result": 1
}
}
```