PHP code example of bfg / resource

1. Go to this page and download the library: Download bfg/resource 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/ */

    

bfg / resource example snippets




namespace App\Http\Resources;

use App\Models\User;
use Bfg\Resource\BfgResource;
use Bfg\Resource\Traits\ModelScopesTrait;
use Bfg\Resource\Traits\EloquentScopesTrait;

/**
 * @mixin User
 */
class UserResource extends BfgResource
{
    use EloquentScopesTrait, ModelScopesTrait;

    /**
     * Map of resource fields
     * @var array
     */
    protected array $map = [

    ];
}

...
    protected array $map = [
        'id',
        'name',
        'email',
        'phone',
        'photo',
        // Variants
        'avatar' => AvatarResource::class, // Use resource
        'avatar' => [AvatarResource::class, 'photo'], // Path to field
        'avatar' => [AvatarResource::class, 'photo.src'], // You can use a dot path, for relations an example
        'avatar' => ['photo.src'], // Or just set a new path for field in array
        'avatar' => 'photo.src', // Or in string
    ];
...

...
    public function getPhotoField ($value) {
        return $value ? asset($value) : asset('images/default_photo.jpg');
    }
...

...
    protected array $casts = [
        'id' => 'int'
    ];
...

...
    protected array $extends = [
        UserResource::class => ['id', 'name'], // Insert only id and name fields
        UserDetailsResource::class => 'phone', // Insert only phone field
        UserCommentResource::class, // Inserted all fields
    ];
...

...
    /**
     * Define your route model bindings, pattern filters, etc.
     *
     * @return void
     */
    public function boot()
    {
        $this->configureRateLimiting();

        $this->routes(function () {
            ...
            Route::find(
                __DIR__.'/../Resources',
                Route::prefix('api')
                    ->middleware(['api', 'auth:sanctum'])
                    ->as('api.')
            );
            
            //Route::prefix('api')
            //    ->middleware('api')
            //    ->namespace($this->namespace)
            //    ->group(base_path('routes/api.php'));            
            ...
        });
    }
...

...
use Bfg\Resource\Attributes\GetResource;

/**
 * @mixin User
 */
#[GetResource] 
class UserResource extends BfgResource
{
    ...
}

...
    protected array $map = [
        '?id', // <--
    ];
...

...
    protected array $temporal = [
        'id', // <--
    ];
...

...
    protected bool $temporal_all = true;
...

...
    public static function getScope($model): mixed
    {
        return $model->get();
    }
...

...
    public static function onlyScope($model, ...$fields): mixed
    {
        return $model?->only($fields);
    }
...

...
    public static function paginateScope(
        $model,
        int $perPage = null,
        string $pageName = 'page',
        int $page = null,
        ...$columns
    ): \Illuminate\Contracts\Pagination\LengthAwarePaginator {
        /** @var Model $model */
        return $model->paginate($perPage, $columns ?: ['*'], $pageName, $page);
    }
...

#[GetResource, CanResource]
class DirectorResource extends BfgResource
{
    ...
}

use Bfg\Resource\Attributes\CanScope;
...
    #[CanScope]
    public static function myScope($model, array $data, int $id): mixed
    {
        return $model;
    }
...

...
    #[CanFields([
        'id', 'name'
    ])] protected array $map = [
        'id',
        'name',
    ];
    // Or
    #[CanFields('id', 'name')] 
    protected array $map = [
        'id',
        'name',
    ];
...

...
    #[CanFields([
        'id', 'name' => 'my-policy'
    ])] protected array $map = [
        'id',
        'name',
    ];
...

#[GetResource, CanUser]
class DirectorResource extends BfgResource
{
    ...
}

#[GetResource, CanUser('local_field', 'user_field')]
class DirectorResource extends BfgResource
{
    ...
}

UserResource::make(User::first());

UserResource::collection(User::get());

UserResource::create(User::first()): static;
// or
UserResource::create(User::get()): BfgResourceCollection;

use App\Http\Resources\UserResource;
...
    // For get resource instance
    UserResource::scope('where', 'name', 'admin', 'first');
    
    // For get resource array result
    UserResource::scope('where', 'name', 'admin', 'first')->toFields();
...

use App\Http\Resources\UserResource;
...
    // For get resource array result
    UserResource::use('where', 'name', 'admin', 'first'); // object with data
...
bash
php artisan make:resource user