A flexible and powerful package for creating dynamic API resources in Laravel. This package extends Laravel's API Resources with features like modular modes (minimal, detailed, etc.), field filtering, and nested resource handling.
- 🔄 Multiple response modes with chainable methods
- 🎯 Field filtering with
only()
andexcept()
- 🔗 Automatic nested resource handling
- 🎨 Additional field support
- 🌲 Collection support with consistent formatting
- ⚡ Fluent interface for easy chaining
- 🔌 Dynamic mode combinations using
with
andwithout
methods
- PHP 8.2 or higher
- Laravel 11.0 or higher
You can install the package via composer:
composer require benyaminrmb/laravel-dynamic-resources
Create a new resource by extending ModularResource
:
use Benyaminrmb\LaravelDynamicResources\ModularResource;
class UserResource extends ModularResource
{
protected function fields(): array
{
return [
'minimal' => [
'id',
'username',
],
'avatar' => [
'profile' => UploadResource::make($this->channel->profile)->minimal(),
],
'rank' => [
'rank' => (int) $this->rank?->rank ?? 0,
],
'default' => [
'id',
'username',
]
];
}
}
// Basic usage with single mode
return UserResource::make($user)->minimal();
// Combining multiple modes
return UserResource::make($user)
->minimal()
->withAvatar()
->withRank();
// Remove specific modes
return UserResource::make($user)
->minimal()
->withAvatar()
->withoutRank();
// Collection usage with modes
return UserResource::collection($users)
->minimal()
->withAvatar()
->withRank();
// Filter specific fields
return UserResource::make($user)
->minimal()
->withAvatar()
->only(['id', 'username', 'profile'])
->additional(['meta' => 'some value']);
You can combine different modes using the following methods:
- Basic modes:
minimal()
,default()
,detailed()
- Add modes:
withAvatar()
,withRank()
, etc. - Remove modes:
withoutAvatar()
,withoutRank()
, etc.
// Include only specific fields
UserResource::make($user)->only(['id', 'name']);
// Exclude specific fields
UserResource::make($user)->except(['created_at', 'updated_at']);
UserResource::make($user)->additional([
'meta' => [
'version' => '1.0',
'api_status' => 'stable'
]
]);
The package automatically handles nested resources and maintains the selected modes throughout the resource tree:
class UserResource extends ModularResource
{
protected function fields(): array
{
return [
'minimal' => [
'id',
'name',
],
'posts' => [
'posts' => PostResource::collection($this->posts),
],
'profile' => [
'profile' => ProfileResource::make($this->profile),
],
'default' => [
'id',
'name',
]
];
}
}
composer test
composer analyse
composer format
Please see CONTRIBUTING for details.
If you discover any security-related issues, please email [email protected] instead of using the issue tracker.
The MIT License (MIT). Please see License File for more information.