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 $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
{
...
}
#[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
Loading please wait ...
Before you can download the PHP files, the dependencies should be resolved. This can take some minutes. Please be patient.