PHP Classes

File: site/guide/data.md

Recommend this page to a friend!
  Packages of Boss Ibrahim Mussa   Caelrik   site/guide/data.md   Download  
File: site/guide/data.md
Role: Auxiliary data
Content type: text/markdown
Description: Auxiliary data
Class: Caelrik
Build Web user interface from PHP components
Author: By
Last change:
Date: 8 days ago
Size: 8,258 bytes
 

 

Contents

Class file image Download

Data endpoints

A component with a url() loads its data from your endpoint. Use the same component definition on the page and in the endpoint: the endpoint then accepts only the declared columns, sorts only sortable ones and pages at the declared size.

Grid

$grid = Grid::make('users')
    ->caption('Users')
    ->url('/users/data')
    ->column('id', 'ID', static fn ($column) => $column->searchable(false))
    ->column('name')
    ->column('email', 'E-mail');

// GET /users/data
header('Content-Type: application/json');
echo json_encode($grid->respond(new ArrayDataSource($rows), $_GET));

respond() reads the request, asks the data source for one page, and keeps only the declared columns in each row, so a source that returns more fields never leaks them.

The response

Every Caelrik endpoint answers with the same envelope:

{
  "data": [{ "id": 1, "name": "Ada Lovelace", "email": "ada@example.com" }],
  "meta": { "page": 1, "perPage": 10, "total": 250, "filtered": 12, "draw": 3, "sort": [], "search": "ada", "filters": {}, "conditions": [] }
}

The request

respond() understands two formats:

  • the DataTables server-side protocol, sent by the grid: `draw`, `start`, `length`, `order[i][column|dir]`, `columns[i][data]`, `search[value]`;
  • a simple format for your own clients: `?page=2&per_page=25&sort=name,-created_at&search=ada&filter[city]=Paris`.

Unknown fields are refused, the search term matches % and _ literally, and a page holds at most DataRequest::MAX_PER_PAGE (1000) rows.

Column filters

The grid sends its column filters as filter[...], in both formats:

filter[customer]=ada                       Filter::text()
filter[status]=paid                        Filter::select([...])
filter[gift]=1                             Filter::boolean(): 1 or 0
filter[ordered_at][from]=2026-01-01        Filter::dateRange(): either end, or both
filter[ordered_at][to]=2026-01-31

respond() reads each one as its column's filter type says, and hands them to the data source in the DataRequest:

  • `$request->filters`: exact values, `field => value` (selects, yes/no filters, and `filter[...]` on other searchable columns);
  • `$request->conditions`: a list of `['field' => ..., 'operator' => ..., 'value' => ...]`, where the operator is `contains` (a text filter, ignoring case), `gte` (on or after a day) or `lt` (before a day). A date range's last day is included: `to=2026-01-31` becomes `lt 2026-02-01`, so times on that day match.

A data source of your own should apply both. DataRequest::containsPattern($value) gives a contains value as a LIKE pattern, to use with ESCAPE '!'.

Totals and groups

A grid with column totals or groups adds two things to the DataRequest:

  • `$request->totals`: the totals to compute, `field => function` (`sum`, `avg`, `count`, `min` or `max`), over every row that passes the search and filters;
  • `$request->groupBy`: the field the rows are grouped by. The request is already sorted by it first.

The data source returns them in the DataResult, which the endpoint's answer carries in meta:

"totals": { "amount": 5045.5 },
"groups": [
  { "value": "Design", "count": 2, "totals": { "amount": 2800 } },
  { "value": "Sales", "count": 3, "totals": { "amount": 2095.5 } }
]

groups lists the groups of the page's rows, each counted and totalled over all its filtered rows. The built-in sources do this in one query per total, and one GROUP BY query for the groups. In a source of your own, Data\Aggregate::compute($function, $values) totals PHP values as SQL does, and a request without totals or a group needs nothing new.

Data sources

| Source | For | |---|---| | Data\ArrayDataSource($rows) | Arrays already in memory | | Adapters\Laravel\EloquentDataSource($query, searchable: ['name', 'email']) | An Eloquent or query builder (Laravel) | | Adapters\Symfony\DoctrineDataSource($queryBuilder, searchable: [...], fieldMap: ['author' => 'a.name']) | A Doctrine query builder (Symfony) |

Write your own by implementing Data\DataSourceInterface::fetch(DataRequest $request): DataResult.

Inline edits

A grid with inline editing sends each change to its inlineEdit() URL as a form-encoded POST:

field=role&value=dir&_method=PATCH&_token=?

$grid->cellEdit($_POST) returns a CellEdit (field, value) for an editable column and a value its editor allows, or throws InvalidCellEdit with a message for the user. Answer:

  • `200` with `$edit->answer()`: `{"value": "dir"}`, or `$edit->answer($saved, 'Role changed.')` with the value as saved and a message;
  • `422` with `$refusal->toArray()`: `{"message": "...", "errors": {"role": ["..."]}}`. A Laravel validation error has the same shape.

Check that the user may change the row, as for any other request: cellEdit() only checks the column and the value.

Actions

A request action (Action::request()), for example a grid's Delete button, sends its method to its URL with these headers: - Accept: application/json; - X-Requested-With: XMLHttpRequest; - the CSRF token, in X-CSRF-TOKEN by default.

The body is the action's form: _method, and the token in _token.

Answer with JSON. A message is shown in a toast, a success for a 2xx status and an error otherwise:

// DELETE /members/{id}
echo json_encode(['message' => 'Ada Lovelace was deleted.']);

A grid's bulk action also sends the keys of the selected rows, ids[]=4&ids[]=9. Check that the user may change each of them.

Chart

A chart with url() fetches {"data": {"labels": [...], "datasets": [...]}} and builds its data table text alternative from it:

Chart::make('signups')->type('bar')->title('Sign-ups per day')->url('/stats/signups');

// GET /stats/signups
echo json_encode(['data' => Chart::make()->labels($days)->dataset('Sign-ups', $counts)->toData()]);

Searchable select

A select with remote() asks GET /authors/options?search=ada as the user types. respond() searches and sorts on the label field only, ignores any other parameter, and answers with the value and label of the first matches:

$author = Field::select('author_id', [])->remote('/authors/options', value: 'id', label: 'name', limit: 20);

// GET /authors/options
echo json_encode($author->respond(new ArrayDataSource($users), $_GET));
// {"data": [{"value": "2", "label": "Ada Lovelace"}], "meta": {...}}

See Form: searchable and multiple selects.

Scheduler

The calendar requests the visible range, ?start=?&end=?, and posts changes as JSON:

$scheduler = Scheduler::make('team')
    ->url('/events')
    ->createUrl('/events/create')
    ->updateUrl('/events/update')
    ->deleteUrl('/events/delete')
    ->csrf($csrfToken);   // sent in the X-CSRF-TOKEN header

// GET /events?start=2026-11-01&end=2026-12-01
try {
    echo json_encode($scheduler->respond(new ArrayEventSource($events), $_GET));
} catch (InvalidArgumentException $e) {
    http_response_code(400); // missing, invalid or too long range
}

Changes arrive as {"id", "title", "start", "end", "allDay"}. Validate them with Data\Event::fromArray(), save them, and answer {"data": event}, or an error status: the calendar then rolls the change back and fires caelrik:scheduler:error.

| Source | For | |---|---| | Data\ArrayEventSource($events) | Events in memory | | Adapters\Laravel\EloquentEventSource($query, ['allDay' => 'all_day']) | Eloquent; map your columns to id, title, start, end, allDay, color, url | | Adapters\Symfony\DoctrineEventSource($queryBuilder, [...]) | Doctrine, with the same mapping |

Security

  • Put endpoints behind your authorization, like any other route.
  • Changes (actions, Scheduler, uploads, the File Manager, the ThemeBuilder) must check the CSRF token: Laravel does it for the `X-CSRF-TOKEN` header; in Symfony and plain PHP check it yourself.
  • Answer bad input with 400 or 422 and a message, not 500.