DEV Community

susheel kumar
susheel kumar

Posted on

Announcing Laravel API Resource Optimizer: Supercharge Your Laravel APIs

I'm thrilled to introduce Laravel API Resource Optimizer, a new open-source package designed to make your Laravel APIs faster, lighter, and more flexible. Whether you're building a REST API for a mobile app, a SaaS platform, or a microservices architecture, this package streamlines API development by enhancing Laravel's built-in API Resource classes with powerful optimization features.

In this post, I'll walk you through what the package does, why it matters, and how you can start using it today to level up your Laravel APIs.

Why Laravel API Resource Optimizer?

Laravel's API Resources are fantastic for transforming Eloquent models into JSON responses, but they lack advanced optimization features out of the box. Developers often find themselves writing repetitive code to handle tasks like:

  • Allowing clients to request specific fields to reduce payload size.
  • Dynamically including related data without over-fetching.
  • Caching responses to improve performance.

The Laravel API Resource Optimizer package addresses these pain points by providing a drop-in solution that makes your APIs more efficient and developer-friendly. Built with performance and simplicity in mind, it’s compatible with Laravel 8.x, 9.x, and 10.x, and it’s ready to use in your next project.

Key Features

Here’s what makes this package stand out:

  • Sparse Fieldsets: Let clients request only the fields they need (e.g., GET /users?fields=id,name), reducing response sizes and improving performance.
  • Conditional Relationship Loading: Include related data on demand (e.g., GET /users?include=posts) to avoid unnecessary database queries.
  • Response Caching: Cache API responses with configurable TTL to minimize server load and speed up requests.
  • Schema Validation: Ensure requested fields and relationships are valid, enhancing security and reliability.
  • Rate-Limiting: Protect your API with built-in throttling to prevent abuse.

These features are designed to work seamlessly with Laravel’s ecosystem, leveraging familiar conventions and requiring minimal setup.

Getting Started

Installing and using the package is a breeze. Here’s a quick guide to get you up and running.

Installation

Install the package via Composer:

composer require sakshsky/laravel-api-optimizer
Enter fullscreen mode Exit fullscreen mode

Optionally, publish the configuration file to customize settings:

php artisan vendor:publish --provider="Sakshsky\ApiOptimizer\ApiOptimizerServiceProvider"
Enter fullscreen mode Exit fullscreen mode

The configuration file (config/api-optimizer.php) lets you tweak options like cache duration and default fields:

return [
    'cache_ttl' => 60, // Cache responses for 60 seconds
    'default_fields' => ['id', 'name'],
    'max_nesting_depth' => 3,
    'rate_limit' => '60,1', // 60 requests per minute
];
Enter fullscreen mode Exit fullscreen mode

Creating an Optimized Resource

Extend the OptimizedResource class to define your API resource:

namespace App\Http\Resources;

use Sakshsky\ApiOptimizer\OptimizedResource;

class UserResource extends OptimizedResource
{
    protected $allowedFields = ['id', 'name', 'email', 'created_at'];
    protected $allowedIncludes = ['posts'];

    public function toArray($request)
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'created_at' => $this->created_at,
            'posts' => PostResource::collection($this->whenLoaded('posts')),
        ];
    }
}
Enter fullscreen mode Exit fullscreen mode

Using in a Controller

Use the resource in your controller like any Laravel API Resource:

namespace App\Http\Controllers;

use App\Http\Resources\UserResource;
use App\Models\User;

class UserController extends Controller
{
    public function index()
    {
        $users = User::query()->paginate();
        return UserResource::collection($users);
    }
}
Enter fullscreen mode Exit fullscreen mode

Example API Requests

Here’s what you can do with the package:

  1. Fetch all fields:
   GET /api/users
Enter fullscreen mode Exit fullscreen mode
   [
       {
           "id": 1,
           "name": "John Doe",
           "email": "john@example.com",
           "created_at": "2025-05-12T12:00:00Z"
       },
       ...
   ]
Enter fullscreen mode Exit fullscreen mode
  1. Request specific fields:
   GET /api/users?fields=id,name
Enter fullscreen mode Exit fullscreen mode
   [
       {
           "id": 1,
           "name": "John Doe"
       },
       ...
   ]
Enter fullscreen mode Exit fullscreen mode
  1. Include relationships:
   GET /api/users?include=posts
Enter fullscreen mode Exit fullscreen mode
   [
       {
           "id": 1,
           "name": "John Doe",
           "email": "john@example.com",
           "posts": [
               {
                   "id": 1,
                   "title": "My First Post"
               },
               ...
           ]
       },
       ...
   ]
Enter fullscreen mode Exit fullscreen mode

Applying Middleware

The package includes an api-optimizer middleware to parse query parameters. Apply it to your routes:

Route::middleware('api-optimizer')->group(function () {
    Route::resource('users', UserController::class);
});
Enter fullscreen mode Exit fullscreen mode

Why This Package Matters

In today’s API-driven world, performance and flexibility are critical. Clients—whether mobile apps or web frontends—expect fast, tailored responses. By supporting sparse fieldsets and conditional includes, Laravel API Resource Optimizer reduces payload sizes and database queries, leading to faster responses and lower server costs. The caching feature is a game-changer for high-traffic APIs, and the schema validation ensures your endpoints stay secure.

Plus, it’s built with Laravel’s developer experience in mind. You don’t need to rewrite your existing resources or learn a new paradigm—just extend OptimizedResource and start optimizing.

What’s Next?

This is just the beginning for Laravel API Resource Optimizer. Future updates may include:

  • GraphQL-like Query Support: Allow structured queries (e.g., ?query={id,name,posts{id,title}}) for even more flexibility.
  • Response Compression: Compress responses to further reduce payload sizes.
  • OpenAPI Integration: Generate Swagger documentation for optimized resources.
  • Multi-Tenancy Support: Optimize APIs for SaaS applications.

I’m excited to hear your feedback and ideas for new features. If you have suggestions, feel free to open an issue or submit a pull request!

Contribute and Connect

Laravel API Resource Optimizer is open-source under the MIT License, and contributions are welcome! Whether you’re fixing bugs, adding features, or improving documentation, your help will make this package even better.

To get started, check out the CONTRIBUTING.md file for guidelines.

Try It Today

Ready to supercharge your Laravel APIs? Install Laravel API Resource Optimizer and see the difference for yourself:

composer require sakshsky/laravel-api-optimizer
Enter fullscreen mode Exit fullscreen mode

I can’t wait to see how you use this package in your projects. Share your experiences, success stories, or questions on X with the hashtag #LaravelApiOptimizer, or drop a comment below.

Happy coding, and let’s make Laravel APIs faster together!


If you enjoyed this post, please share it with the Laravel community and star the GitHub repository. Stay tuned for more updates!

Top comments (0)