Skip to content

Series The AQC Files · Part 3 of 15

All series →
Laravel Query Builder Design Patterns Redundant Reusable Atomic Query Construction (AQC)

Atomic Query Construction (AQC) Explained: One Class per Query in Laravel

Raheel Shan

Raheel Shan

April 25th, 2025 · 3 min read

Atomic Query Construction (AQC) Explained: One Class per Query in Laravel

Atomic Query Construction (AQC) is a design pattern where every query in your application lives in its own class. The class accepts parameters, builds the query for the situation described by those parameters, and returns the result through a single handle() method. Controllers, jobs, exports and APIs call that class instead of writing their own queries. This post explains the idea and then builds a complete example in Laravel, covering an admin panel, a storefront and a mobile API from one class.

Quick answer

  1. Create one class per query, for example App\AQC\Product\GetAllProducts.
  2. Give it a static handle(array $params) method that returns the results.
  3. Let the parameters select the filters, the columns (a "scenario") and the sorting.
  4. Call the class from every place that needs that data. Never rewrite the query elsewhere.

What is AQC?

AQC stands for Atomic Query Construction. "Atomic" means one query, one class, one reason to change. Each class follows the same rules: it accepts parameters, constructs the query internally, returns results, and is the only place that query exists. If you want the story behind the idea, read Introducing the Atomic Query Construction (AQC) Design Pattern.

The philosophy fits in one line: you ask for a scenario, and the class gives you exactly the result that scenario needs.

The problem: one resource, many callers

Take a typical e-commerce system with three parts: an admin control panel (ACP), a public storefront (EW) and a mobile app (MA). All three read the same products table, but in different ways:

  • ACP: paginated lists, filters by category and brand, Excel exports, dropdowns, and reports for low stock, out of stock and expired products.
  • Storefront: trending, new arrivals and featured sections, keyword search, category pages, sorting by price, and related products.
  • Mobile app: the same cases as the storefront, returned as JSON.

Without a pattern, that logic spreads across controllers, services, resources, exports and report generators. When a column or filter changes, you have to find every copy. With AQC there is one file to change.

The AQC class

Here is the class for the product list. It lives in app/AQC/Product/GetAllProducts.php.

<?php

namespace App\AQC\Product;

use App\Models\Product;

class GetAllProducts
{
    private const SORTABLE = ['id', 'name', 'price', 'stock'];

    public static function handle(array $params = [])
    {
        $query = Product::query()->latest('id');

        self::applyFilters($query, $params);
        self::selectColumns($query, $params);
        self::applySorting($query, $params);

        $paginate = filter_var($params['paginate'] ?? true, FILTER_VALIDATE_BOOLEAN);

        if (! $paginate) {
            return $query->get();
        }

        $perPage = min((int) ($params['per_page'] ?? 15), 100);

        return $query->paginate($perPage, ['*'], 'page', $params['page'] ?? null);
    }

    private static function applyFilters($query, array $params): void
    {
        if (($params['category_id'] ?? 0) > 0) {
            $query->where('category_id', $params['category_id']);
        }

        if (($params['brand_id'] ?? 0) > 0) {
            $query->where('brand_id', $params['brand_id']);
        }

        if (! empty($params['keyword'])) {
            $keyword = '%'.$params['keyword'].'%';

            // Grouped, so the OR conditions never leak past the other filters.
            $query->where(function ($q) use ($keyword) {
                $q->where('name', 'like', $keyword)
                    ->orWhere('sku', 'like', $keyword)
                    ->orWhere('description', 'like', $keyword);
            });
        }

        if (! empty($params['low_stock'])) {
            $query->whereColumn('stock', '<=', 'low_stock_point');
        }

        if (! empty($params['out_of_stock'])) {
            $query->where('stock', 0);
        }

        if (! empty($params['expired'])) {
            $query->whereDate('expired_date', '<', today());
        }

        if (! empty($params['featured'])) {
            $query->where('is_featured', true);
        }

        if (! empty($params['trending'])) {
            $query->where('is_trending', true);
        }

        if (! empty($params['product_id'])) {
            $query->where('related_product_id', $params['product_id']);
        }
    }

    private static function selectColumns($query, array $params): void
    {
        $columns = match ($params['scenario'] ?? 'default') {
            'minimal' => ['id', 'name'],
            'compact' => ['id', 'name', 'price', 'image'],
            'export'  => ['id', 'name', 'price', 'sku', 'cost'],
            'admin'   => ['id', 'name', 'price', 'sku', 'image', 'stock', 'cost'],
            default   => ['*'],
        };

        $query->select($columns);
    }

    private static function applySorting($query, array $params): void
    {
        $sortBy = $params['sortBy'] ?? null;
        $type = strtolower($params['type'] ?? 'asc') === 'desc' ? 'desc' : 'asc';

        if (in_array($sortBy, self::SORTABLE, true)) {
            $query->orderBy($sortBy, $type);
        }
    }
}

The scenario parameter is the heart of the pattern. It decides which columns each caller gets, so the export does not load the same data as a dropdown.

The controller, helper and route

The controller stays thin. It passes the request input to the class and returns the result. Pass only the keys you accept, never the whole request.

<?php

namespace App\Http\Controllers;

use App\AQC\Product\GetAllProducts;
use App\Core\ResponseHelper;
use Illuminate\Http\Request;

class ProductController extends Controller
{
    public function index(Request $request)
    {
        $params = $request->only([
            'category_id', 'brand_id', 'keyword', 'sortBy', 'type',
            'scenario', 'paginate', 'per_page', 'page',
        ]);

        return ResponseHelper::handle('products.index', [
            'products' => GetAllProducts::handle($params),
        ]);
    }
}

The helper returns JSON for API requests and a view for everything else, which is how the same class serves the website and the mobile app:

<?php

namespace App\Core;

class ResponseHelper
{
    public static function handle(string $view, array $data)
    {
        if (request()->is('api/*')) {
            return response()->json($data);
        }

        return view($view, $data);
    }
}
Route::get('/products', [\App\Http\Controllers\ProductController::class, 'index']);

Calling the class for each scenario

Flags such as low_stock or trending are set by your own code, not by the visitor, so call the class directly where you need them.

use App\AQC\Product\GetAllProducts;

// ACP: low stock products for the admin table
$lowStock = GetAllProducts::handle(['low_stock' => true, 'scenario' => 'admin']);

// ACP: export everything, no pagination
$export = GetAllProducts::handle(['scenario' => 'export', 'paginate' => false]);

// ACP: sorted by stock, highest first
$byStock = GetAllProducts::handle(['sortBy' => 'stock', 'type' => 'desc', 'scenario' => 'admin']);

// Storefront: trending products
$trending = GetAllProducts::handle(['trending' => true, 'scenario' => 'compact', 'paginate' => false]);

// Storefront: keyword search
$results = GetAllProducts::handle(['keyword' => 'ink pen', 'scenario' => 'compact']);

// Storefront: related products
$related = GetAllProducts::handle(['product_id' => 1, 'scenario' => 'compact', 'paginate' => false]);

The mobile app hits the same controller under /api/products. The only difference is that ResponseHelper returns JSON.

Mistakes this version fixes

The first version of this post had bugs that are easy to copy by accident:

  • The keyword search used orWhere without grouping, so it ignored the category and brand filters. Always wrap OR conditions in a closure.
  • Comparing stock to 'low_stock_point' as a string compares it to a literal. Use whereColumn to compare two columns.
  • Calling ->get() inside a filter runs the query and throws the result away.
  • isset($params['paginate']) is true even when the value is false, so exports were still paginated. Read the value as a boolean.
  • User-supplied sortBy went straight into orderBy. Whitelist the columns.

Limits and when not to use it

  • A small app with two or three simple queries does not need a class for each. AQC pays off when the same data is read in several places.
  • One parameterised class can grow large. When it does, split it by use case, see How to Prevent AQC Classes from Becoming Too Large.
  • AQC decides where query code lives. It does not replace validation or authorization.

To see AQC used for create, update and delete as well, read the practical CRUD implementation guide. To compare it with similar patterns, see Repository Pattern vs AQC.

FAQ

What is Atomic Query Construction? A design pattern that puts each query in its own class, with one handle() method that accepts parameters and returns results. It keeps query logic in one place.

What is an atomic query? In AQC, an atomic query is a single self-contained query class. It does one job and is the only place that query is written.

How is AQC different from the Repository Pattern? A repository groups many methods for one model. AQC uses one class per query, so each class stays small and easy to find. The full comparison is in Repository Pattern vs AQC.

How is AQC different from CQRS? CQRS separates reading and writing across the whole architecture. AQC is lighter and focuses on organising queries. See Atomic Query Construction vs CQRS.

Does AQC replace Eloquent? No. The class still uses Eloquent or the query builder inside handle(). AQC only decides where that code lives.

Get the free AQC Lite

A short free PDF with the query leak, why repositories overgrow and the four rules of AQC, with a working class you can copy.

Download AQC Lite, free

Want the whole pattern? Get the AQC book

Move your queries to AQC

I created Atomic Query Construction, and I will take you through it on your own code.

Bring one controller where the filters keep piling up. In 60 minutes we move its queries into AQC classes, one class per query.

Book an AQC Adoption call

Found this useful?

Support the work that goes into these posts.

Support
Comments


Comment created and will be displayed once approved.
Built with Brandidos