PHP code example of benyaminrmb / laravel-dynamic-resources

1. Go to this page and download the library: Download benyaminrmb/laravel-dynamic-resources 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/ */

    

benyaminrmb / laravel-dynamic-resources example snippets




namespace App\Http\Resources;

use Benyaminrmb\LaravelDynamicResources\Attributes\View;
use Benyaminrmb\LaravelDynamicResources\DynamicResource;

class UserResource extends DynamicResource
{
    #[View(default: true, requestable: true)]
    protected function standardFields(): array
    {
        return ['id', 'name', 'family', 'email'];
    }

    #[View(requestable: true)]
    protected function minimalFields(): array
    {
        return ['id', 'name', 'family'];
    }

    #[View]
    protected function avatarFields(): array
    {
        return ['avatar'];
    }

    #[View(requestable: true)]
    protected function minimalWithAvatarFields(): array
    {
        return $this->combine(
            $this->minimalFields(),
            $this->avatarFields(),
        );
    }

    #[View]
    protected function detailedFields(): array
    {
        return $this->combine($this->standardFields(), [
            'bio',
            'posts' => $this->relation(
                'posts',
                view: PostResource::VIEW_MINIMAL,
            ),
        ]);
    }

    // <dynamic-resource-views>
    // Constants and fluent selector methods are generated here.
    // </dynamic-resource-views>
}

return UserResource::make($user)
    ->view(UserResource::VIEW_MINIMAL);

return UserResource::make($user)
    ->minimal()
    ->withAvatar();

return UserResource::make($user)->view([
    UserResource::VIEW_MINIMAL,
    UserResource::VIEW_AVATAR,
]);

return UserResource::collection($users)
    ->view(UserResource::VIEW_MINIMAL)
    ->withView([UserResource::VIEW_AVATAR, UserResource::VIEW_TIMESTAMPS]);

return [
    'id',
    'display_name' => fn () => trim("{$this->name} {$this->family}"),
    'avatar' => $this->when($this->avatar !== null, $this->avatar),
    'posts_count' => $this->whenCounted('posts'),
];

'posts' => $this->relation('posts', view: PostResource::VIEW_MINIMAL),

return UserResource::make($user)
    ->view(UserResource::VIEW_DETAILED)
    ->only(['id', 'name']);

return UserResource::collection($users)
    ->except(['email']);

return UserResource::make($user)->fromRequest($request);
bash
php artisan dynamic-resources:sync
bash
php artisan dynamic-resources:sync --check
bash
php artisan make:dynamic-resource UserResource --model=User
php artisan make:dynamic-resource UserResource --views=minimal,default,detailed
php artisan dynamic-resources:list --views
php artisan dynamic-resources:sync
php artisan dynamic-resources:sync --check