← All projectsProject 03 / 03

Grape

Typed data validation and sanitisation for PHP 8.2+, with zero dependencies. Born in Potager.

Screenshot of Grape
Role
Design, development and documentation
Stack
PHP 8.2 · Composer · Pest · PHPStan · VitePress
Licence
MIT
Links
Documentation ↗GitHub ↗Packagist ↗

The project

Grape started as Potager’s validation layer, then grew enough to stand on its own: a Composer library you can use in any PHP project.

You describe the expected shape of your data with a schema, much like Zod in JavaScript. Grape checks the input, cleans it along the way and returns clean, typed data, or a precise tree of errors, field by field.

Features

  1. 01Declarative, chainable schemas with IDE autocompletion
  2. 02Sanitisation during validation: trim(), lowercase(), clamp(), compact()
  3. 03Two styles: exceptions, or an [$error, $data] tuple with check()
  4. 04Loose mode that casts HTTP strings ("42" → 42), or strict mode
  5. 05Nested schemas, collections and tuples; errors as a tree, flat, or fail-fast

Usage

Installation
$ composer require potagerphp/grape
Validating a request
use Potager\Grape\Grape;

$schema = Grape::schema([
    'name'  => Grape::string()->trim()->minLength(2)->required(),
    'email' => Grape::string()->trim()->lowercase()->email()->required(),
    'role'  => Grape::literal('admin', 'editor', 'viewer')->default('viewer'),
]);

[$error, $data] = $schema->check($_POST);

Next project — 01 / 03

Symbiosa