PHP code example of mutado / laravel-resource-schema

1. Go to this page and download the library: Download mutado/laravel-resource-schema library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

mutado / laravel-resource-schema example snippets


    php Mutado\LaravelResourceSchema\SchemaResource;
    
    class UserResource extends SchemaResource
    {
        // Define the schema types for the resource
        protected ?array $schemaTypes = [
            'mini' => [
                'id',
                'name',
            ],
            'full' => [
                'id',
                'name',
                'email',
                'posts',
                'created_at',
            ],
        ];
    
        protected function schema(Request $request): array
        {
            return [
                'id' => $this->id,
                'image' => fn() => ImageResource::make($this->image),
                'name' => $this->name,
                'email' => $this->email,
                // Use closure to lazy load the posts
                'posts' => fn() => PostResource::collection($this->posts),
                'created_at' => $this->created_at,
            ];
        }
    }
    

    public function show(User $user)
    {
        // Use the schema type 'full' and ']);
    }
    

protected ?array $schemaTypes = [
    'post' => [
        'id',
        'title',
        'content',
        // Set the schema type for the author
        'author/mini',
        // Set the schema for comments
        'comments' => [
            'id',
            'content',
            'author/mini',
        ]
    ]
];

// In this example we don't es = [
    'profile' => [
        'id',
        'name',
        '?email',
        'posts',
        'created_at',
    ]
];

protected function show(User $user)
{
    return UserResource::make($user)
        ->useSchemaType('profile')
        // Email only 

protected function show(User $user)
{
    return UserResource::make($user)
        ->useSchemaType([
            'id',
            'name',
            '?email',
            'posts/mini',
            'created_at',
        ]);
}

protected ?array $schemaTypes = [
    '?friends.avatar/mini_profile',
]