Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Enhanced Resources Laravel Package

sourcetoad/enhanced-resources

Laravel API resource enhancement that lets a single Resource expose multiple output “formats” via PHP attributes. Mark methods with #[Format], pick formats with ->format('name'), and optionally set a default with #[IsDefault] to avoid exceptions.

View on GitHub
Deep Wiki
Context7
## Getting Started

### **First Steps**
1. **Installation**
   ```bash
   composer require sourcetoad/enhanced-resources:^7.3.0

Publish the config (if needed):

php artisan vendor:publish --provider="SourceToad\EnhancedResources\EnhancedResourcesServiceProvider" --tag="config"
  1. Basic Usage Extend Laravel’s built-in Resource class with enhanced features (now fully compatible with Laravel 13.x):

    use SourceToad\EnhancedResources\Resource;
    
    class UserResource extends Resource
    {
        public function toArray($request)
        {
            return [
                'id' => $this->id,
                'name' => $this->name,
                'email' => $this->email,
                'meta' => $this->metaData(), // Custom method
                'links' => $this->links(),   // Auto-generated links
            ];
        }
    }
    
  2. First Use Case Replace a standard JsonResource with EnhancedResource to leverage:

    • Automatic metadata (e.g., timestamps, relationships).
    • Dynamic field filtering (e.g., ?fields=id,name).
    • Nested resource support with minimal boilerplate.
    • Laravel 13.x compatibility (e.g., new query builder improvements).

Implementation Patterns

1. Dynamic Field Filtering

Use query parameters to control output fields (now optimized for Laravel 13.x query builder):

// In your controller
public function index(Request $request)
{
    $users = User::query()->get(); // Laravel 13.x query builder
    return new CollectionResource(UserResource::class, $users, $request);
}

Request: GET /users?fields=id,name Output: Only id and name fields are included.

2. Nested Resources

Automatically resolve nested relationships with Laravel 13.x optimizations:

class UserResource extends Resource
{
    public function toArray($request)
    {
        return [
            'id' => $this,
            'posts' => PostResource::collection($this->whenLoaded('posts')),
        ];
    }
}

Enhanced Behavior:

  • Lazy-loads relationships (e.g., posts only if requested).
  • Supports circular references (e.g., User → Posts → User).
  • Leverages Laravel 13.x’s improved relationship handling.

3. Conditional Fields

Hide/show fields based on logic (now compatible with Laravel 13.x request handling):

public function toArray($request)
{
    return [
        'name' => $this->name,
        'email' => $this->when(fn () => $request->user()->isAdmin(), $this->email),
    ];
}

4. Custom Metadata

Add dynamic metadata to responses (now with Laravel 13.x carbon compatibility):

protected function metaData()
{
    return [
        'created_at' => $this->created_at->toIso8601String(),
        'is_active' => $this->isActive(),
    ];
}

5. Pagination Enhancements

Extend Laravel’s pagination with extra metadata (now compatible with Laravel 13.x pagination):

return new PaginatedResource(
    UserResource::class,
    User::paginate(10),
    $request,
    [
        'meta' => [
            'total_pages' => ceil(User::count() / 10),
            'filters_applied' => $request->query(),
        ],
    ]
);

6. API Versioning

Use traits to support versioned responses (now with Laravel 13.x routing improvements):

use SourceToad\EnhancedResources\Traits\Versionable;

class UserResource extends Resource
{
    use Versionable;

    protected $version = 'v2';
}

7. Laravel 13.x Query Builder Improvements

Leverage new Laravel 13.x query builder features:

// Example: Using Laravel 13.x's new query builder methods
$users = User::query()
    ->when($request->has('active'), fn($q) => $q->where('active', true))
    ->get();

Gotchas and Tips

Pitfalls

  1. Circular References

    • Issue: Infinite loops when resources reference each other (e.g., User → Posts → User).
    • Fix: Use ->except() or ->only() to break cycles:
      class PostResource extends Resource
      {
          public function toArray($request)
          {
              return [
                  'id' => $this->id,
                  'user' => UserResource::make($this->user)->except('posts'), // Avoid recursion
              ];
          }
      }
      
  2. Performance with Nested Resources

    • Issue: N+1 queries when eager-loading nested resources.
    • Fix: Use with() in your query (Laravel 13.x optimizations apply):
      User::with(['posts.comments' => fn($q) => $q->orderBy('created_at', 'desc')])->get();
      
  3. Field Filtering Overhead

    • Issue: Dynamic field filtering adds runtime reflection.
    • Fix: Cache compiled resources or use ->only() for static APIs.
  4. Laravel 13.x Configuration Conflicts

    • Issue: Default config may conflict with Laravel 13.x service provider changes.
    • Fix: Publish and merge configs:
      // config/enhanced-resources.php
      'default_fields' => ['id', 'name'], // Override defaults
      'laravel_13_compatibility' => true, // Enable if needed
      
  5. Carbon Compatibility

    • Issue: Carbon 3.x (Laravel 13.x default) may require adjustments in date handling.
    • Fix: Ensure date methods are Carbon-compatible:
      $this->created_at->toIso8601String(); // Works with Carbon 3.x
      

Debugging Tips

  1. Log Resource Output Use Laravel’s dd() or dump() to inspect the resource structure:

    $resource = new UserResource(User::first());
    dump($resource->toArray(new Request()));
    
  2. Check for Deprecated Methods

    • The package may deprecate methods between minor versions. Check the CHANGELOG.
    • Laravel 13.x introduces breaking changes; test thoroughly.
  3. Enable Query Logging Debug N+1 issues with:

    DB::enableQueryLog();
    // ... run your request ...
    dd(DB::getQueryLog());
    
  4. Laravel 13.x Route Caching

    • If using route caching, clear it after updates:
      php artisan route:clear
      

Extension Points

  1. Custom Directives Extend field filtering with custom directives (now compatible with Laravel 13.x):

    // In config/enhanced-resources.php
    'directives' => [
        'uppercase' => fn ($value) => strtoupper($value),
    ];
    

    Usage in Resource:

    'name' => $this->name->uppercase(),
    
  2. Middleware for Resources Apply middleware to resource responses (Laravel 13.x middleware improvements):

    class TransformResponseMiddleware
    {
        public function handle($request, Closure $next)
        {
            $response = $next($request);
            if ($response instanceof ResourceResponse) {
                $response->withHeader('X-Resource-Type', get_class($response->resource));
            }
            return $response;
        }
    }
    
  3. Event Hooks Listen to resource compilation events (now with Laravel 13.x event improvements):

    EnhancedResources::listen('compiling', function ($resource, $request) {
        if ($request->has('debug')) {
            $resource->addMeta('debug', true);
        }
    });
    
  4. Testing Resources Use the ResourceTestCase helper (compatible with Laravel 13.x testing):

    use SourceToad\EnhancedResources\Testing\ResourceTestCase;
    
    class UserResourceTest extends ResourceTestCase
    {
        public function test_fields_are_filtered()
        {
            $response = $this->get('/users?fields=id,name');
            $response->assertJsonStructure(['data' => [[
                'id', 'name'
            ]]]);
        }
    }
    
  5. Laravel 13.x Testing Improvements Leverage Laravel 13.x’s new testing features:

    public function test_resource_with_laravel_13_features()
    {
        $response = $this->actingAs(User::factory()->create())
            ->getJson('/users');
        $response->assertOk();
    }
    
  6. **CI/CD

Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
terminal42/code-quality-tools
codifyo/ts-generator-bundle
andydefer/laravel-cluster
testo/fiber
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky