Skip to content

Lesson 3 of 9 · 24m

GraphQL in PHP: Power With a Meter Attached

Use GraphQL when clients genuinely need flexible selection, then contain its cost with schema design, depth limits, persisted operations, and resolver discipline.

GraphQL is not 'REST but newer.' It is a different trade: clients gain precise selection and composition, while the server inherits query cost, authorization complexity, and caching problems that REST makes easier. Reach for it when multiple clients truly need different views of the same graph — not because a team is tired of versioning endpoints.

The schema is the product

With webonyx/graphql-php, the schema defines what clients can ask for. Keep fields deliberate and nullable only when absence is meaningful.

$invoiceType = new ObjectType([
    'name' => 'Invoice',
    'fields' => [
        'id' => Type::nonNull(Type::id()),
        'number' => Type::nonNull(Type::string()),
        'status' => Type::nonNull(Type::string()),
        'totalCents' => Type::nonNull(Type::int()),
        'lines' => [
            'type' => Type::nonNull(Type::listOf(Type::nonNull($invoiceLineType))),
            'resolve' => fn (Invoice $invoice) => $invoice->lines()->limit(100),
        ],
    ],
]);

A nullable field means every client has to handle absence. Excessive nullability is usually a sign the domain model or permissions model is muddled.

N+1 is the default failure mode

GraphQL resolvers invite N+1 queries because each field can trigger data access. A query for 50 invoices and their customers can become 51 queries unless you batch.

// DataLoader-style batching: collect keys during a tick, load once
$customerLoader->load($invoice->customerId);

// later, one SQL query:
SELECT id, name, email FROM customers WHERE id IN (?, ?, ?, ...);

If your GraphQL server does not have a batching strategy, production traffic will eventually write one for you in the form of an incident.

Constrain expensive queries before deployment

REST endpoints have predictable shapes. GraphQL queries do not. Clients can nest selections until the server collapses.

query BadIdea {
  users { posts { comments { author { posts { comments { id } } } } } }
}

Use depth limits, complexity analysis, timeouts, and query cost budgets. For first-party clients, persisted operations are stronger: the server executes only allowlisted query documents identified by hash, which removes whole classes of ad hoc abuse.

Authorization belongs at the field edge

REST often authorizes at the route level. GraphQL cannot stop there because one HTTP request may touch many resources. Check access when resolving each object or field, not only once at /graphql. Be careful with hidden data: returning null for a forbidden field can be correct, but sometimes rejecting the operation is less confusing.

Field notes

  • GraphQL errors can return HTTP 200 with an errors array. Monitor errors, not just status codes.
  • Caching is harder because identical URLs can mean different queries. Use persisted query hashes and cache only data that is safe across viewers.
  • Do not mirror your database schema one-to-one. Design a client-facing graph; joins and tables are implementation details.
  • Mutations should accept input objects and return the changed object plus errors in a predictable shape.

Was this lesson helpful?

Sign in to rate