---
title: Integrate SurveyJS with Laravel
description: Learn how to connect SurveyJS to a Laravel backend to collect answers, display results, edit forms, and run SurveyJS on the server.
source: https://surveyjs.io/documentation/backend-integration-php-laravel
---

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Integrate SurveyJS with %7B%40 backend %40%7D&value=backend:Laravel --->

# Integrate SurveyJS with Laravel

SurveyJS libraries enable you to display and edit web forms, collect answers, analyze results, and generate PDF forms in the browser. Your backend supplies the data these libraries need and stores the changes they produce. The libraries exchange JSON with your backend, which allows you to use any database and storage services.

This guide explains how to integrate SurveyJS with your Laravel backend. It walks through all backend-specific workflows, starting with the minimum integration: saving a completed response. Each workflow description provides client and server code samples and a link to a live example.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Integrate SurveyJS with %7B%40 backend %40%7D&value=backend:Laravel --->

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Run Forms --->

## Run Forms

[SurveyJS Form Library](/form-library/documentation/overview) displays a form using a JSON schema and collects the respondent's answers. Start integration by adding an endpoint that saves those answers. You can then load data from the server, save progress in unfinished forms, and add the other features described below if your application needs them.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Run Forms --->

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Save Responses --->

### Save Responses

To collect responses, your backend needs an endpoint that accepts and stores answers. The form JSON schema can be a JavaScript constant on the page for now—this first step does not require an endpoint for loading it.

When the respondent completes the form, SurveyJS raises the [`onComplete`](/form-library/documentation/api-reference/survey-data-model#onComplete) event. Handle it to send `survey.data` and the form ID to your save endpoint. The backend should store the answers as a single JSON document and return the saved response's ID to confirm that the save succeeded.

> Store the response exactly as it arrives—spaces, empty strings, and empty objects may be meaningful.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Save Responses --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/save-response.js#L5-L50 --->

```js
import { Model } from "survey-core";

// Define the form directly in the page - no database needed
const definition = {
  title: "Contact us",
  completeText: "Send message",
  elements: [
    {
      type: "text",
      name: "email",
      title: "Your email",
      inputType: "email",
      isRequired: true
    },
    {
      type: "comment",
      name: "message",
      title: "How can we help?",
      isRequired: true
    }
  ]
};
const survey = new Model(definition);

// Save after completion; SurveyJS offers a retry action if saving fails
survey.onComplete.add(async (sender, options) => {
  sender.setVariable("responseId", null);
  sender.completedHtml = "<h3>Sending your message...</h3>";
  options.showSaveInProgress("Sending your message...");
  try {
    const response = await fetch("/api/responses", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ formId: "contact", data: sender.data })
    });
    if (!response.ok) throw new Error("Save failed");
    const { id } = await response.json();
    if (!Number.isInteger(id) || id < 1) throw new Error("Missing response ID");
    sender.setVariable("responseId", id);
    sender.completedHtml = `<h3>Your message has been saved.</h3><p>Response ID: ${id}</p>`;
    options.showSaveSuccess();
  } catch {
    sender.completedHtml = "<h3>Your message hasn't been saved.</h3>";
    options.showSaveError("We couldn't save your message. Please try again.");
  }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/save-response.js#L5-L50 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/save-response.php#L10-L20 --->

```php
// POST /api/responses: Store submitted answers as one JSON document
// The middleware in bootstrap/app.php disables TrimStrings and ConvertEmptyStringsToNull to preserve spaces and empty strings
Route::post('/api/responses', function (Request $request) {
    // Read the raw request body to prevent PHP arrays from turning {} into [] in stored JSON
    $body = json_decode($request->getContent(), flags: JSON_THROW_ON_ERROR);
    abort_unless(isset($body->formId, $body->data), 400, 'Expected { formId, data }');

    $id = StoredJson::insertResponse($body->formId, $body->data);   // Preserve float values such as 1.0

    return response()->json(['id' => $id], 201);
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/save-response.php#L10-L20 --->

</details>

[Live Example: Save Responses](https://surveyjs-php.demos.surveyjs.io/examples/save-response (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Load JSON Schemas%2C Variables%2C and Answers --->

### Load JSON Schemas, Variables, and Answers

As your application grows, the same form may need to dynamically change, behave differently for different users, or open with answers already filled in. Your backend can provide the JSON schema, variables, and previous answers needed to prepare the form.

- JSON schema\
  Form JSON schema describes the questions, layout, and logic. You can include the schema in the page when the latter renders or fetch it from an endpoint before displaying the form. In either case, the server can dynamically adjust the schema for the current request.

- Variables\
  Variables provide context for the form. For example, the current user's name can appear in a title, and their subscription plan can control which questions are visible. Variables are excluded from the saved answers.

- Previous answers\
  If the user is returning to an existing record, also load its answers and assign them to `survey.data`. The form then opens with those values already filled in.

An endpoint can return all three pieces of data in one request.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Load JSON Schemas%2C Variables%2C and Answers --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/load-definition-variables-data.js#L5-L21 --->

```js
import { Model } from "survey-core";

async function createSurvey(recordId) {
  if (window.FORM_DEFINITION) {
    // Option A: Use the schema and user variables embedded in the HTML response
    const survey = new Model(window.FORM_DEFINITION);
    survey.setVariables(window.FORM_VARIABLES);
    return survey;
  }
  // Option B: Load the definition, variables, and previous answers in one request
  const { definition, variables, data } =
    await fetch(`/api/forms/claim-request?record=${encodeURIComponent(recordId)}`).then(r => r.json());
  const survey = new Model(definition);
  survey.setVariables(variables);   // Variables are available in expressions such as {user.name} and are excluded from survey.data
  survey.data = data;               // Restore previously saved answers for editing
  return survey;
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/load-definition-variables-data.js#L5-L21 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/load-definition-variables-data.php#L12-L34 --->

```php
// Option A: Embed the schema and user variables in the HTML response
Route::get('/claim', function () {
    $definition = json_decode(file_get_contents(base_path('shared/definitions/load-definition-variables-data.json')));
    $user = Auth::user();
    $variables = ['user' => ['name' => $user?->name, 'plan' => $user?->plan]];

    return view('examples.load-definition-variables-data', compact('definition', 'variables'));   // Use Js::from() in the view to escape JSON for an inline script
});

// Option B: Return the definition, variables, and previous answers in one response
Route::get('/api/forms/{id}', function (Request $request, string $id) {
    $user = Auth::user();
    $definition = DB::table('forms')->where('key', $id)->value('json') ?? abort(404, 'Unknown form');
    $record = DB::table('responses')->where('id', $request->query('record'))
        ->when($id === 'claim-request', fn ($q) => $q->where('form_id', 'claim')->where('data->customer_email', $user?->email));
    $data = $request->filled('record') ? $record->value('data') : null;

    return StoredJson::response([
        'definition' => json_decode($definition),                                // Return the stored form definition
        'variables' => ['user' => ['name' => $user?->name, 'plan' => $user?->plan]],
        'data' => $data === null ? new stdClass : json_decode($data),           // Return previous answers, or {} when none are available
    ]);
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/load-definition-variables-data.php#L12-L34 --->

</details>

[Live Example: Load JSON Schemas, Variables, and Answers](https://surveyjs-php.demos.surveyjs.io/examples/load-definition-variables-data (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Resume Progress --->

### Resume Progress

With long forms, respondents may need to stop and return later. You can save their answers together with the form's UI state, which includes the current page and focused input field. Restoring both lets them continue from the same place.

While the respondent works, listen for answer and page changes and send the updated progress to the backend. Answer changes can happen on every keystroke, so wait for a short pause before saving. Send any pending changes when users close or reload the browser tab as well.

The backend should store one progress document for each user and form. When the respondent returns, load that document and restore the answers and UI state before they continue.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Resume Progress --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/resume-progress.js#L100-L122 --->

```js
import debounce from "lodash/debounce";

const saveProgress = debounce(() => flushProgress().catch(showSaveError), 800);
function flushProgress() {
  saveProgress.cancel();
  if (pendingProgress === null) return saving ?? Promise.resolve();
  return saving ??= persistProgress().finally(() => { saving = null; });
}
function queueProgress() {
  if (!recording || locked) return;
  const body = JSON.stringify(snapshot());
  if (body === lastSnapshot) return;
  lastSnapshot = pendingProgress = body;
  setStatus("Changes will be saved automatically");
  saveProgress();
}
survey.onValueChanged.add(queueProgress);
survey.onUIStateChanged.add(queueProgress);   // Include page and focus changes
document.addEventListener("visibilitychange", () => {
  if (document.visibilityState === "hidden" && recording && !locked) {
    flushProgress().catch(showSaveError);
  }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/resume-progress.js#L100-L122 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/resume-progress.php#L12-L28 --->

```php
// Return the current user's saved answers and UI state
Route::get('/api/progress/{formId}', function (string $formId) {
    $key = (Auth::id() ?? abort(401, 'Sign in to load progress')).':'.$formId;
    $json = DB::table('progress')->where('key', $key)->value('json');

    return response($json ?? 'null')->header('Content-Type', 'application/json');
});

// Store progress under a key containing both the user ID and form ID
Route::put('/api/progress/{formId}', function (Request $request, string $formId) {
    $key = (Auth::id() ?? abort(401, 'Sign in to save progress')).':'.$formId;
    // Read the raw request body to prevent PHP arrays from turning {} into [] in stored JSON
    $progress = json_decode($request->getContent(), flags: JSON_THROW_ON_ERROR);
    StoredJson::put('progress', $key, $progress);   // Preserve float values such as 1.0

    return response()->noContent();
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/resume-progress.php#L12-L28 --->

</details>

[Live Example: Resume Progress](https://surveyjs-php.demos.surveyjs.io/examples/resume-progress (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Store Files Separately --->

### Store Files Separately

A [File Upload](/form-library/examples/file-upload/) question can store file contents in the response as Base64 strings. This makes responses much larger. Alternatively, you can keep files in a separate storage. To do this, set the question's [`storeDataAsText`](/form-library/documentation/api-reference/file-model#storeDataAsText) property to `false` and handle the survey's [`onUploadFiles`](/form-library/documentation/api-reference/survey-data-model#onUploadFiles) event.

The event handler should send selected files to an upload endpoint. The backend stores each file and returns its ID or URL. The form saves that reference in the answers, leaving the file contents out of the response document.

For private files, use IDs and a download endpoint that checks the user's access before returning a file. Handle the [`onDownloadFile`](/form-library/documentation/api-reference/survey-data-model#onDownloadFile) event to retrieve the content when the form needs to display a preview.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Store Files Separately --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/store-files.js#L9-L20 --->

```js
// Upload: your server stores the files and returns an id (or a URL) for each
survey.onUploadFiles.add(async (_, options) => {
  const body = new FormData();
  options.files.forEach(file => body.append("files[]", file));   // "files[]": PHP keeps only the last of several "files"
  const response = await fetch("/api/files", { method: "POST", body }).catch(() => null);
  const ids = response?.ok ? await response.json().catch(() => null) : null;
  if (!Array.isArray(ids) || ids.length !== options.files.length || ids.some(id => typeof id !== "string" || !id)) {
    return options.callback([], ["Couldn't upload files. Please try again."]);
  }
  // The response stores these ids, not the file contents
  options.callback(options.files.map((file, i) => ({ file, content: ids[i] })));
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/store-files.js#L9-L20 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/store-files.php#L14-L36 --->

```php
// POST /api/files — store uploads, return their ids in the same order
Route::post('/api/files', function (Request $request) {
    $validation = Validator::make($request->all(), [
        'files' => 'required|array|min:1',
        'files.*' => 'required|file|max:5120|mimetypes:'
            .'image/png,image/jpeg,image/webp,image/gif,application/pdf',
    ]);
    abort_if($validation->fails(), 422, $validation->errors()->first());
    $ids = [];
    // Field "files[]": PHP keeps only the last of several "files"
    foreach ($request->file('files') as $file) {
        abort_unless($file->isValid(), 400, $file->getErrorMessage());
        $id = (string) Str::uuid();
        // The "uploads" disk: local, S3…; named by id, never by the client
        $file->storeAs('', $id, 'uploads');
        DB::table('files')->insert([
            'id' => $id, 'name' => $file->getClientOriginalName(), 'type' => $file->getMimeType(),
        ]);
        $ids[] = $id;
    }

    return response()->json($ids);
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/store-files.php#L14-L36 --->

</details>

[Live Example: Store Files Separately](https://surveyjs-php.demos.surveyjs.io/examples/store-files (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Load Choices from Web --->

### Load Choices from Web

Choice lists often come from data your application already stores, such as products or offices. Use the [`choicesByUrl`](/form-library/documentation/api-reference/dropdown-menu-model#choicesByUrl) property to load those options into a Dropdown, Checkboxes, or Radio Button Group question. The configured endpoint should return the list, and SurveyJS displays it as the question's choices.

The URL can include answers or variables in curly braces. For example, `/api/offices?region={region}` uses the selected region to request matching offices. When that answer changes, SurveyJS requests the list again.

The browser calls the URL directly. If an external service needs a secret key or does not allow cross-origin requests, have your backend call it and return the choices to the browser. If your own endpoint requires authentication headers, add them through [`settings.web.onBeforeRequestChoices`](/form-library/documentation/api-reference/settings#web).

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Load Choices from Web --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/choices-from-web.js#L9-L18 --->

```js
// Use choicesByUrl in the form definition to load lists from API endpoints
//   "choicesByUrl": { "url": "/api/offices?region={region}", "valueName": "id", "titleName": "name" }
//   "choicesByUrl": { "url": "/api/countries", "valueName": "code", "titleName": "name" }
// SurveyJS replaces {region} with the selected region and reloads the office list when the region changes

// Optional: add your auth header to every choices request
import { settings } from "survey-core";
settings.web.onBeforeRequestChoices = (_, options) => {
  options.request?.setRequestHeader("Authorization", `Bearer ${token}`);
};
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/choices-from-web.js#L9-L18 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/choices-from-web.php#L13-L32 --->

```php
// GET /api/offices?region= — {region} from the form arrives as a query parameter
Route::get('/api/offices', function (Request $request) {
    return DB::table('offices')->where('region', $request->query('region', ''))->orderBy('name')->get(['id', 'name']);
});

// GET /api/countries — a proxy: the browser can't call a service without CORS, your server can
Route::get('/api/countries', function () {
    try {
        $countries = Cache::remember('countries', now()->addDay(), fn () => Http::timeout(5)
            ->get('https://restcountries.com/v3.1/all', ['fields' => 'name,cca2'])->throw()->collect()
            ->map(fn (array $country) => ['code' => $country['cca2'], 'name' => $country['name']['common']])
            ->sortBy('name')->values()->all());
    } catch (Throwable $e) {   // down, or a different answer: serve the bundled list for 10 minutes, so requests don't each wait for the timeout
        Log::warning('restcountries.com failed; serving shared/seed/countries.json', ['error' => $e->getMessage()]);
        $countries = json_decode(file_get_contents(base_path('shared/seed/countries.json')), true);
        Cache::put('countries', $countries, now()->addMinutes(10));
    }

    return response()->json($countries)->header('Cache-Control', 'public, max-age=86400');
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/choices-from-web.php#L13-L32 --->

</details>

[Live Example: Load Choices from Web](https://surveyjs-php.demos.surveyjs.io/examples/choices-from-web (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Async Calculations and Validation --->

### Async Calculations and Validation

Some form logic needs information that only your backend has. For example, a validation rule may need to check whether an email address is already registered, or a calculation may need the shipping rate for a postcode.

Register an expression function with `isAsync: true` and have it request that information from your backend. The function returns a promise. When the request finishes, SurveyJS uses the result to update the calculation, validation rule, or visibility condition that called the function.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Async Calculations and Validation --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/async-functions.js#L58-L78 --->

```js
// Validate email availability using the backend's customer records
registerFunction({
  name: "emailExists",
  isAsync: true,
  func: async ([email]) => {
    const key = normalize("email", email);
    if (!key) return false;
    return lookup("email", key, `/api/customers/exists?email=${encodeURIComponent(key)}`, "exists");
  }
});

// Share one shipping lookup between the calculation and the postcode validator
registerFunction({
  name: "shippingCost",
  isAsync: true,
  func: async ([postcode]) => {
    const key = normalize("postcode", postcode);
    if (!key) return null;
    return lookup("postcode", key, `/api/shipping?postcode=${encodeURIComponent(key)}`, "price");
  }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/async-functions.js#L58-L78 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/async-functions.php#L11-L32 --->

```php
// GET /api/customers/exists?email= — answers emailExists()
Route::get('/api/customers/exists', function (Request $request) {
    $email = Str::lower(trim((string) $request->query('email')));

    return ['exists' => DB::table('customers')->where('email', $email)->exists()];
});

// GET /api/shipping?postcode= — answers shippingCost(): the longest matching postcode prefix wins,
// { "price": null } when none matches (the form shows "We don't deliver to this postcode yet")
Route::get('/api/shipping', function (Request $request) {
    $postcode = Str::upper(str_replace(' ', '', (string) $request->query('postcode')));
    // only a whole German (10115) or UK (SW1A 1AA) postcode gets a price, not anything that starts with a prefix
    if (! preg_match('/^(\d{5}|[A-Z]{1,2}\d[A-Z\d]?\d[A-Z]{2})$/', $postcode)) {
        return ['price' => null];
    }
    $rate = DB::table('shipping_rates')->get()
        ->filter(fn ($rate) => str_starts_with($postcode, $rate->postcode_prefix))
        ->sortByDesc(fn ($rate) => strlen($rate->postcode_prefix))
        ->first();

    return ['price' => $rate ? (float) $rate->price : null];
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/async-functions.php#L11-L32 --->

</details>

[Live Example: Async Calculations and Validation](https://surveyjs-php.demos.surveyjs.io/examples/async-functions (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Use Relational Storage --->

### Use Relational Storage

Storing each response as JSON is enough to preserve its answers. If you also need to query those answers with SQL or join them with other application data, copy the relevant values into database columns.

First, give the answers stable keys. A question's [`valueName`](/form-library/documentation/api-reference/question#valueName) sets the key it writes into the response independently of its question name. Form authors can then rename or move questions without breaking the mapping to your columns. If you need more mapping information, add a custom question property and expose it in Survey Creator's Property Grid.

When saving, keep the original JSON and the version of the form JSON schema used to collect it. Then copy the mapped values into their columns. Save both in one transaction, so the records stay consistent. Keeping the original document and schema version also lets you rebuild the mapping if your tables change later.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Use Relational Storage --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/relational-storage.js#L10-L17 --->

```js
import { Model, Serializer } from "survey-core";

// Optional metadata describing the columns used by the PHP route
Serializer.addProperty("question", { name: "dbColumn", category: "data" });

// Keep answer keys stable when question names change
const survey = new Model(definitions[definitionVersion]);
survey.completeText = "Submit claim";
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/relational-storage.js#L10-L17 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/relational-storage.php#L11-L31 --->

```php
// POST /api/claims — original JSON first, then the columns you query
Route::post('/api/claims', function (Request $request) {
    // The raw body, not $request->input(): PHP arrays would turn {} into [] in the stored JSON
    $body = json_decode($request->getContent(), flags: JSON_THROW_ON_ERROR);
    abort_unless(isset($body->data, $body->definitionVersion), 400, 'Expected { data, definitionVersion }');

    $id = DB::transaction(function () use ($body) {
        $responseId = StoredJson::insertResponse('claim', $body->data, [          // the original, stored as it arrived: 1.0 stays 1.0
            'definition_version' => $body->definitionVersion,                    // keep the original and its version
        ]);
        DB::table('claims')->insert([                                            // keys come from valueName
            'response_id' => $responseId,
            'customer_email' => $body->data->customer_email ?? null,
            'amount' => $body->data->amount ?? null,
        ]);

        return $responseId;
    });

    return response()->json(['id' => $id], 201);
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/relational-storage.php#L11-L31 --->

</details>

[Live Example: Use Relational Storage](https://surveyjs-php.demos.surveyjs.io/examples/relational-storage (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Fill Forms Together --->

### Fill Forms Together

Several people may need to fill out the same record, such as a dispatcher and a technician completing a job sheet. Participants see each other's answers, focus, and cursors.

To let participants fill out a form together, follow these steps:

1. Add `CollaborationPlugin` from `survey-core/collaboration` to enable this functionality.
1. Connect the clients to a WebSocket relay that groups participants by record. When someone joins, the relay sends the form JSON schema and current answers so that their form starts in the same state as everyone else's.
1. Have the relay keep the latest value for each question and forward changes to the other clients. If two people change the same question, the last change wins.
1. Save the completed response through the usual save endpoint.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Fill Forms Together --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/fill-together.js#L74-L97 --->

```js
// Transport the plugin's answer and presence messages over a WebSocket
function applySharedState(message) {
  const draft = survey?.data;
  const previousSession = sessionId;
  if (!collab) {
    survey = new Model(message.seed);
    survey.completeText = "Finish job sheet";
    collab = new CollaborationPlugin(survey, { getInviteLink: partnerLink });
    collab.onEvent.add((_, { message }) => {
      if (ready && responseId === null && ws.readyState === WebSocket.OPEN) ws.send(JSON.stringify(message));
    });
    survey.onComplete.add(completeJobSheet);
    mountSurvey(survey);
  }
  sessionId = message.sessionId;
  ready = true;
  collab.apply(message);
  // Restore the local draft if an empty session replaces the disconnected one
  if (previousSession && previousSession !== sessionId && !message.responseId && !message.peers.length) survey.data = draft;
  form.hidden = false;
  document.getElementById("collaboration-loading").hidden = true;
  setLocked(false);
  if (message.responseId) confirmCompletion(message.responseId, message.values);
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/fill-together.js#L74-L97 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/app/Relay/FillRelay.php#L25-L84 --->

```php
// Run the relay as its own process and relay JSON: php artisan relay:fill
private array $rooms = [];   // room key => Room { seed, values, clients }

public function onConnect(TcpConnection $c, Request $request): void
{
    $user = $this->user($request);                                       // may this user open this record?
    $recordId = $this->recordId($request);
    $roomKey = $recordId === null ? null : RoomKey::fromHandshake($request, $recordId);
    if (! $user || $roomKey === null) {
        $c->close();

        return;
    }
    $room = $this->rooms[$roomKey] ??= new Room(...$this->seed($recordId));   // the definition + the saved answers
    $room->cancelDrop();                                                  // back within 2 s: keep the room
    $c->context->roomKey = $roomKey;
    $c->context->id = bin2hex(random_bytes(8));
    $c->context->name = self::name($request->get('name'), $user->name);
    $c->context->slot = $room->freeSlot();
    $c->context->state = null;
    $room->clients[$c->id] = $c;
    $this->send($c, ['type' => 'init', 'clientId' => $c->context->id, 'name' => $c->context->name,
        'colorIndex' => Room::colorIndex($c->context->slot), 'seed' => $room->seed,
        'values' => $room->snapshot(), 'peers' => $room->roster($c),
        'sessionId' => $room->sessionId, 'responseId' => $room->responseId]);
}

public function onMessage(TcpConnection $from, string $raw): void
{
    $msg = json_decode($raw);                                                // objects stay objects: {} is relayed as {}
    $room = $this->rooms[$from->context->roomKey ?? ''] ?? null;
    if (! $room || ! $msg instanceof stdClass) {
        return;
    }
    if (($msg->type ?? '') === 'complete' && ($msg->data ?? null) instanceof stdClass) {
        $this->complete($from, $room, $msg->data);
    } elseif (($msg->type ?? '') === 'value' && is_string($msg->key ?? null) && $room->responseId === null) {
        $room->values[$msg->key] = $msg->value ?? null;
        $room->broadcast($from, ['type' => 'value', 'from' => $from->context->id, 'key' => $msg->key, 'value' => $msg->value ?? null]);
    } elseif (($msg->type ?? '') === 'presence' && isset($msg->state) && strlen($raw) <= 4096) {   // stamp identity, relay
        $retain = ($msg->retain ?? true) !== false;
        if ($retain) {
            $from->context->state = $msg->state;
        }
        $room->broadcast($from, ['type' => 'peer', 'retain' => $retain, 'peer' => Room::peer($from, $msg->state)], droppable: ! $retain);
    }                                                                        // unknown types: ignore
}

public function onClose(TcpConnection $c): void
{
    $room = $this->rooms[$c->context->roomKey ?? ''] ?? null;
    if (! $room) {
        return;
    }
    unset($room->clients[$c->id]);
    $room->broadcast($c, ['type' => 'peer-left', 'clientId' => $c->context->id]);
    if (count($room->clients) === 0) {                                      // drop the room 2 s after the last person leaves
        $room->dropTimer = Timer::add(2, fn () => count($room->clients) === 0 && $this->drop($c->context->roomKey), [], false);
    }
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/app/Relay/FillRelay.php#L25-L84 --->

</details>

[Live Example: Fill Forms Together](https://surveyjs-php.demos.surveyjs.io/examples/fill-together (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Analyze Results with Dashboard --->

## Analyze Results with Dashboard

Once you have collected responses, use [SurveyJS Dashboard](/dashboard/documentation/overview) to display and analyze them. Dashboard runs in the browser and uses the form JSON schema to choose a chart for each question automatically.

Load the JSON schema and request the saved responses for that form. The backend should return the answers as a JSON array, which the client passes to Dashboard along with the schema.

As the number of responses grows, you can filter or paginate them on the server. This lets users load the data they need without sending every stored response to the browser.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Analyze Results with Dashboard --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/dashboard.js#L23-L46 --->

```js
// Load answers with their submission dates for Dashboard's built-in date filter
async function loadResults(signal) {
  const query = new URLSearchParams({ formId: "feedback", includeCreatedAt: "1", limit: "5000" });
  const [definition, response] = await Promise.all([
    loadSchema(), fetch(`/api/responses?${query}`, { signal })
  ]);
  if (!response.ok) throw new Error("Responses load failed");
  const data = await response.json();
  if (!Array.isArray(data)) throw new Error("Invalid responses");
  return { definition, data: data.map(row => ({ ...row.data, createdAt: row.createdAt })) };
}

function renderResults(definition, data) {
  if (!dashboard) {
    const survey = new Model(definition);
    dashboard = new Dashboard({
      questions: survey.getAllQuestions(), data,
      dateFieldName: "createdAt", datePeriod: "last30days"
    });
    dashboard.render(container);
  } else {
    dashboard.updateData(data);
  }
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/dashboard.js#L23-L46 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/dashboard.php#L10-L30 --->

```php
// GET /api/responses?formId=&includeCreatedAt=&from=&to=&limit=&offset=
Route::get('/api/responses', function (Request $request) {
    $documents = DB::table('responses')
        ->where('form_id', $request->query('formId'))
        ->where('created_at', '>=', $request->query('from', '1970-01-01'))   // ISO-8601 UTC strings compare as dates
        ->when($request->filled('to'), fn ($query) => $query->whereDate('created_at', '<=', $request->query('to')))
        ->orderBy('created_at')
        ->limit(min(max((int) $request->query('limit', 500), 1), 5000))       // filter or page on the server for large volumes
        ->offset(max((int) $request->query('offset', 0), 0))
        ->get(['data', 'created_at']);

    // Include submission dates separately when requested by Dashboard
    if ($request->boolean('includeCreatedAt')) {
        return response()->json($documents->map(fn ($row) => [
            'data' => json_decode($row->data), 'createdAt' => $row->created_at,
        ]));
    }

    return response('['.$documents->pluck('data')->implode(',').']')         // documents as stored, not re-encoded
        ->header('Content-Type', 'application/json');
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/dashboard.php#L10-L30 --->

</details>

[Live Example: Analyze Results with Dashboard](https://surveyjs-php.demos.surveyjs.io/examples/dashboard (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Edit Forms in Survey Creator --->

## Edit Forms in Survey Creator

[Survey Creator](/survey-creator/documentation/overview) lets authors build and edit forms in your application. It works with the same form JSON schemas that Form Library displays to respondents. Your backend should load those schemas when the editor opens and save them when an author makes changes.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Edit Forms in Survey Creator --->

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Load and Save Form JSON Schemas --->

### Load and Save Form JSON Schemas

Start by loading the saved schema into Survey Creator. You can use the [same endpoint that supplies the schema to Form Library](#load-json-schemas-variables-and-answers).

When the author clicks **Save**, Survey Creator calls [`saveSurveyFunc`](/survey-creator/documentation/api-reference/survey-creator#saveSurveyFunc). Use this function to send the updated JSON schema to your backend. The backend should check the author's permission to edit forms, store the JSON, and confirm that it was saved. The next time a respondent opens the form, Form Library loads the updated JSON schema.

To save after each change, set the [`autoSaveEnabled`](/survey-creator/documentation/api-reference/survey-creator#autoSaveEnabled) property to `true`. Survey Creator then calls the same save function automatically. If the backend rejects a save, the backend should report the failure to Survey Creator so that the author can see it.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Load and Save Form JSON Schemas --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/creator-load-save.js#L22-L35 --->

```js
const creator = new SurveyCreator({ showTranslationTab: true });
// Queue writes so an older request cannot overwrite newer edits
const saver = createSchemaSaver(() => creator.JSON, async json => {
  const response = await fetch(`/api/forms/${formId}`, {
    method: "PUT",
    headers: { "Content-Type": "application/json" },
    body: json
  });
  if ([401, 403].includes(response.status)) saveDenied = true;
  if (!response.ok) throw await responseError(response, "Couldn't save the form schema. Please try again.");
}, updateSaveState);
creator.saveSurveyFunc = (saveNo, callback) => {
  saver.save().then(saved => callback(saveNo, saved));
};
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/creator-load-save.js#L22-L35 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/creator-load-save.php#L14-L22 --->

```php
// PUT /api/forms/{id} — store the definition as-is: it's one JSON document
Route::put('/api/forms/{id}', function (Request $request, string $id) {
    Gate::authorize('edit-forms'); // editing is an admin action: 403 otherwise
    // The raw body, not $request->input(): PHP arrays would turn {} into [] in the stored JSON
    $definition = json_decode($request->getContent(), flags: JSON_THROW_ON_ERROR);
    StoredJson::put('forms', $id, $definition); // stored as it arrived: 1.0 stays 1.0

    return response()->noContent(); // the next page load renders the new version
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/creator-load-save.php#L14-L22 --->

</details>

[Live Example: Load and Save Form JSON Schemas](https://surveyjs-php.demos.surveyjs.io/examples/creator-load-save (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Upload Files --->

### Upload Files

Authors may need to add a logo, image, or file to a form. You can keep these files in your storage and save their URLs in the JSON schema to keep it small.

When an author selects a file, Survey Creator raises the [`onUploadFile`](/survey-creator/documentation/api-reference/survey-creator#onUploadFile) event. Handle it by sending the file to your upload endpoint, then pass the returned URL back to Survey Creator. Survey Creator adds the URL to the JSON schema, and the next save preserves that reference.

You can reuse the [storage endpoint for respondent uploads](#store-files-separately). If the file is private, its URL should point to a download endpoint that checks access before serving the file.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Upload Files --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/creator-uploads.js#L36-L59 --->

```js
// Store each uploaded image separately and keep its URL in the form schema
creator.onUploadFile.add(async (_, options) => {
  const label = options.propertyName === "logo" || options.elementType === "header" ? "Logo" : "Image";
  uploads++; updateControls();
  showError("");
  try {
    if (!options.files.length || options.files.some(file =>
      file.size > 5242880 || !["image/png", "image/jpeg", "image/webp", "image/gif"].includes(file.type)))
      throw new Error("Choose a PNG, JPEG, WebP, or GIF image up to 5 MB.");
    const body = new FormData();
    options.files.forEach(file => body.append("files[]", file));
    const response = await fetch("/api/files", { method: "POST", body });
    const ids = response.ok ? await response.json() : null;
    if (!Array.isArray(ids) || ids.length !== options.files.length ||
      ids.some(id => typeof id !== "string" || !id))
      throw new Error(`Couldn't upload the ${label.toLowerCase()}. Please try again.`);
    options.callback("success", `/api/files/${encodeURIComponent(ids[0])}`);
    note(`${label} uploaded.`, "ok");
  } catch (error) {
    options.callback("error");
    showError(error.message);
    note(error.message, "error");
  } finally { uploads--; updateControls(); }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/creator-uploads.js#L36-L59 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/store-files.php#L14-L36 --->

```php
// POST /api/files — store uploads, return their ids in the same order
Route::post('/api/files', function (Request $request) {
    $validation = Validator::make($request->all(), [
        'files' => 'required|array|min:1',
        'files.*' => 'required|file|max:5120|mimetypes:'
            .'image/png,image/jpeg,image/webp,image/gif,application/pdf',
    ]);
    abort_if($validation->fails(), 422, $validation->errors()->first());
    $ids = [];
    // Field "files[]": PHP keeps only the last of several "files"
    foreach ($request->file('files') as $file) {
        abort_unless($file->isValid(), 400, $file->getErrorMessage());
        $id = (string) Str::uuid();
        // The "uploads" disk: local, S3…; named by id, never by the client
        $file->storeAs('', $id, 'uploads');
        DB::table('files')->insert([
            'id' => $id, 'name' => $file->getClientOriginalName(), 'type' => $file->getMimeType(),
        ]);
        $ids[] = $id;
    }

    return response()->json($ids);
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/store-files.php#L14-L36 --->

</details>

[Live Example: Upload Files](https://surveyjs-php.demos.surveyjs.io/examples/creator-uploads (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Translate with AI --->

### Translate with AI

For multilingual forms, you can integrate AI in Survey Creator's **Translations** tab so that authors can translate titles, choices, and other form text semi-automatically.

When an author requests a translation, send the source strings and language information to your backend. The backend should call the AI provider you choose and return the translated strings in their original order. Keep the provider's API key on the server.

Authors can review and edit the translations in the UI before using them in the form.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Translate with AI --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/ai-translation.js#L27-L45 --->

```js
// Return translated strings in the original order, and always finish the callback
creator.onMachineTranslate.add(async (_, options) => {
  showError("");
  try {
    const response = await fetch("/api/translate", {
      method: "POST", headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ strings: options.strings, from: options.fromLocale, to: options.toLocale })
    });
    if (!response.ok) throw await responseError(response, "AI translation failed. Please try again.");
    const strings = await response.json();
    if (!Array.isArray(strings) || strings.length !== options.strings.length || strings.some(text => typeof text !== "string"))
      throw new Error("The translation provider returned an invalid result. Please try again.");
    options.callback(strings);
  } catch (error) {
    options.callback([]);
    showError(`${translationError(error)} Existing translations are kept.`);
    note(error.message, "error");
  }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/ai-translation.js#L27-L45 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/ai-translation.php#L10-L19 --->

```php
// POST /api/translate — strings in, translated strings out (same order); nothing goes to SurveyJS
Route::post('/api/translate', function (Request $request) {
    abort_unless(config('surveyjs.ai.api_key'), 501, 'Set AI_API_KEY to enable translation');
    ['strings' => $strings, 'from' => $from, 'to' => $to] = $request->only(['strings', 'from', 'to']) + ['strings' => [], 'from' => '', 'to' => ''];

    $translated = AiTranslation::translate($strings, $from, $to);            // any OpenAI-compatible provider: your key, your choice
    abort_unless(is_array($translated) && count($translated) === count($strings) && count(array_filter($translated, 'is_string')) === count($strings), 502, 'The AI provider returned an unexpected answer');

    return response()->json($translated);                                    // what options.callback() takes
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/ai-translation.php#L10-L19 --->

</details>

[Live Example: Translate with AI](https://surveyjs-php.demos.surveyjs.io/examples/ai-translation (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Variable Presets --->

### Variable Presets

Form logic may depend on variables supplied by your application, such as a customer's subscription plan. Authors need sample values to test that logic before the form is used. Variable presets allow them to do that by providing named sets of those values in Survey Creator.

Load the saved presets from the backend when the editor opens. In the **Preview** tab, an author can select a preset to see how the form behaves with its values. Switching presets updates the preview using data already loaded in the browser.

When an author edits a preset, you need to save the updated presets to your backend as a JSON document. Check editing permission before saving, just as you do for form JSON schemas.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Variable Presets --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/variable-presets.js#L14-L29 --->

```js
const creator = new SurveyCreator({
  variablePresets: {
    definition: {
      elements: [{
        type: "dropdown", name: "customerTier", title: "Customer plan",
        choices: [{ value: "basic", text: "Basic" }, { value: "premium", text: "Premium" }],
        isRequired: true
      }]
    },
    presets: []
  }
});
creator.onVariablePresetsChanged.add((_, options) => {
  // Switching scenarios changes only Preview; editing persists the preset list
  if (loaded && options.reason === "edit") { saver.changed(); saver.save(); }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/variable-presets.js#L14-L29 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/variable-presets.php#L12-L27 --->

```php
// GET /api/variable-presets/{formId} — return the stored preset list, or [] when none are saved
Route::get('/api/variable-presets/{formId}', function (string $formId) {
    $json = DB::table('variable_presets')->where('key', $formId)->value('json') ?? '[]';

    return response($json)->header('Content-Type', 'application/json');
});

// PUT /api/variable-presets/{formId} — store the variable presets as-is: it's one JSON document
Route::put('/api/variable-presets/{formId}', function (Request $request, string $formId) {
    Gate::authorize('edit-forms');                                           // editing is an admin action: 403 otherwise
    // The raw body, not $request->input(): PHP arrays would turn {} into [] in the stored JSON
    $presets = json_decode($request->getContent(), flags: JSON_THROW_ON_ERROR);
    StoredJson::put('variable_presets', $formId, $presets);                  // stored as it arrived: 1.0 stays 1.0

    return response()->noContent();
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/variable-presets.php#L12-L27 --->

</details>

[Live Example: Variable Presets](https://surveyjs-php.demos.surveyjs.io/examples/variable-presets (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Edit Forms Together --->

### Edit Forms Together

Several authors can work on the same form. Participants see each other's edits, selection, and cursors, and cannot edit survey elements that another participant is editing.

To let several authors work on the same form, follow these steps:

1. Add `CollaborationPlugin` from `survey-creator-core/collaboration` to enable this functionality.
1. Connect the clients to a WebSocket relay. Have the relay add each edit to a change log as a JSON record and forward it to the other participants.
1. When someone joins, send them the starting JSON schema and the change log. Applying those changes brings the new participant's editor up to date.
1. Save the JSON schema through `saveSurveyFunc` and your usual save endpoint. After the collaboration session ends, the next session starts from the saved schema.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Edit Forms Together --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/edit-together.js#L59-L81 --->

```js
// Rebuild the shared form from its saved schema and ordered edit log
function initialize(message) {
  creator?.dispose();
  creator = new SurveyCreator({ showTranslationTab: true });
  creator.JSON = message.seed;
  collab = new CollaborationPlugin(creator, { roomId: formId, getInviteLink: sharedFormLink });
  creator.addPlugin("collaboration", collab);
  collab.setClientId(message.clientId);
  configureSaving();
  saver.markSaved();
  if (message.log.length) collab.apply(message.log);
  const history = new Map();
  function addHistory(records) {
    for (const record of records) history.set(`${record.seq}:${record.op}:${record.payload?.target ?? ""}`, record);
    collab.setHistory([...history.values()]);
  }
  addHistory(message.log);
  const append = (_, { record }) => { send({ type: "append", payload: record }); addHistory([record]); };
  collab.onRecordAdded.add(append);
  collab.onRecordChanged.add(append);
  collab.onStateChanged.add(() => send({ type: "presence", state: collab.getState() }));
  return addHistory;
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/edit-together.js#L59-L81 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/app/Relay/EditRelay.php#L22-L78 --->

```php
// The same kind of relay as Fill Forms Together, keeping an append-only log instead of a value map:
// Creator records must be replayed in order. Run as its own process: php artisan relay:edit
private array $rooms = [];   // room key => EditRoom { seed, log, clients }

public function onConnect(TcpConnection $c, Request $request): void
{
    $user = $this->editor($request);                                     // may this user edit this form?
    $formId = $this->formId($request);
    $roomKey = $formId === null ? null : RoomKey::fromHandshake($request, $formId);
    if (! $user || $roomKey === null) {
        $c->close();

        return;
    }
    $room = $this->rooms[$roomKey] ??= new EditRoom($this->savedDefinition($formId));   // seed = saved definition
    $room->cancelDrop();                                                  // back within 2 s: keep the room
    $c->context->roomKey = $roomKey;
    $c->context->id = bin2hex(random_bytes(8));
    $c->context->name = self::name($request->get('name'), $user->name);
    $c->context->slot = $room->freeSlot();
    $c->context->state = null;
    $room->clients[$c->id] = $c;
    $this->send($c, ['type' => 'init', 'clientId' => $c->context->id, 'colorIndex' => $c->context->slot,
        'color' => EditRoom::PALETTE[$c->context->slot], 'seed' => $room->seed, 'log' => $room->log]);   // init first
    if ($peers = $room->roster($c)) {
        $this->send($c, ['type' => 'presence-sync', 'peers' => $peers]);
    }
}

public function onMessage(TcpConnection $from, string $raw): void
{
    $msg = json_decode($raw);                                                // records stay opaque: {} is relayed as {}
    $room = $this->rooms[$from->context->roomKey ?? ''] ?? null;
    if (! $room || ! $msg instanceof stdClass) {
        return;
    }
    if (($msg->type ?? '') === 'append' && isset($msg->payload)) {          // append, then fan out
        $room->log[] = $msg->payload;
        $room->broadcast($from, ['type' => 'record', 'from' => $from->context->id, 'payload' => $msg->payload]);
    } elseif (($msg->type ?? '') === 'presence' && isset($msg->state) && strlen($raw) <= 4096) {
        $from->context->state = $msg->state;
        $room->broadcast($from, ['type' => 'presence', 'peer' => EditRoom::peer($from)]);
    }                                                                        // unknown types: ignore
}

public function onClose(TcpConnection $c): void
{
    $room = $this->rooms[$c->context->roomKey ?? ''] ?? null;
    if (! $room) {
        return;
    }
    unset($room->clients[$c->id]);
    $room->broadcast($c, ['type' => 'presence-leave', 'clientId' => $c->context->id]);
    if (count($room->clients) === 0) {                                      // the log lives until the room empties
        $room->dropTimer = Timer::add(2, fn () => count($room->clients) === 0 && $this->drop($c->context->roomKey), [], false);
    }
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/app/Relay/EditRelay.php#L22-L78 --->

</details>

[Live Example: Edit Forms Together](https://surveyjs-php.demos.surveyjs.io/examples/edit-together (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Run Server-Side Workflows --->

## Run Server-Side Workflows

Some workflows need SurveyJS logic on the server. You may need to check a submission before storing it, find problems in a form JSON schema, create a PDF, or read answers from a document.

These operations run in Node.js. A Node.js backend can run the components directly; other backends can call a Node.js service over HTTP. In either case, your backend supplies the required data and uses the result in its own workflow.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Run Server-Side Workflows --->

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Validate Responses --->

### Validate Responses

Browser validation helps respondents correct their answers while filling out a form. Your API can also receive requests that bypass the form, so you need to repeat validation on the server before storing a response.

When a submission arrives, load the form JSON schema from your storage. Validate the submitted answers against that schema on the server, checking required questions, value types, and allowed choices.

Save the response only if validation succeeds. If it fails, return the errors to the client so that the respondent can correct the answers.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Validate Responses --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/validate-response.js#L46-L61 --->

```js
// Confirm a save only after the backend accepts the answers and returns a response ID
survey.onComplete.add(async (sender, options) => {
  lock(true);
  sender.completedHtml = "<h3>Submitting your claim...</h3>";
  options.showSaveInProgress();
  try {
    const result = await submit(sender.data);
    if (result.rejected) throw new Error(result.errors.map(describe).join("; "));
    sender.completedHtml = `<h3>Your claim has been saved.</h3><p>Response ID: ${result.id}</p>`;
    options.showSaveSuccess();
  } catch (error) {
    sender.completedHtml = "<h3>Your claim hasn't been saved.</h3>";
    const message = error instanceof TypeError ? "Couldn't validate the response. Please try again." : error.message;
    options.showSaveError(message);
  } finally { lock(false); }
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/validate-response.js#L46-L61 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/validate-response.php#L15-L30 --->

```php
// POST /api/responses — ask the SurveyJS service to validate, then store as usual
Route::post('/api/responses', function (Request $request) {
    $body = json_decode($request->getContent(), flags: JSON_THROW_ON_ERROR);    // the raw body keeps {} as {} (see Save Responses)
    abort_unless(is_object($body) && is_string($body->formId ?? null) && is_object($body->data ?? null), 400, 'Expected { formId, data } with an answers object');
    $definition = DB::table('forms')->where('key', $body->formId ?? null)->value('json') ?? abort(404, 'Unknown form');
    $check = SurveyJsService::post('/response', ['schema' => json_decode($definition), 'response' => $body->data ?? null], timeout: 10);
    if ($check->status() === 422 && $check->json('errors') !== null && ! array_key_exists('warnings', $check->json())) {
        return response()->json(['errors' => $check->object()->errors], 400);    // the answers don't fit the definition
    }
    if ($check->status() !== 200 || $check->body() !== '{}') {                  // fail closed: only exactly {} means valid
        SurveyJsService::unexpected('/response', $check, $check->status() === 422 && $check->json('warnings') !== null ? 'The stored definition has errors' : 'SurveyJS service error');
    }
    $id = StoredJson::insertResponse($body->formId, $body->data);               // stored as it arrived: 1.0 stays 1.0

    return response()->json(['id' => $id], 201);
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/validate-response.php#L15-L30 --->

</details>

[Live Example: Validate Responses](https://surveyjs-php.demos.surveyjs.io/examples/validate-response (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Lint JSON Schemas --->

### Lint JSON Schemas

A form JSON schema can contain mistakes that stop its questions or logic from working as intended. For example, a condition may refer to a question that does not exist. Check JSON schemas using the [SurveyJS Linter](/form-library/documentation/survey-json-validation#use-the-surveyjs-linter) before saving and return its findings to Survey Creator so that authors can fix these problems before respondents encounter them.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Lint JSON Schemas --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/lint-definition.js#L34-L50 --->

```js
// Display the server's errors and warnings and return the actual save result to Creator
async function saveDefinition(definition) {
  const response = await fetch(`/api/forms/${formId}`, {
    method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify(definition)
  });
  const report = response.status === 204 ? {} : await response.json();
  reportFindings(report);
  if (response.status === 422 && Array.isArray(report.errors) && report.errors.length) {
    note("Form schema not saved. Fix the reported errors and retry.", "error");
    return false;
  }
  if (!response.ok) throw new Error(report.error || "Couldn't save the form schema. Please try again.");
  const count = report.warnings?.length ?? 0;
  note(count ? `Schema saved with ${count} warning${count === 1 ? "" : "s"}. Review the findings above.` : "Form schema saved successfully.", "ok");
  return true;
}
creator.saveSurveyFunc = async (saveNo, callback) => callback(saveNo, await checkAndSave(creator.JSON));
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/lint-definition.js#L34-L50 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/lint-definition.php#L14-L29 --->

```php
// PUT /api/forms/{id} — lint the definition from Creator before storing it
Route::put('/api/forms/{id}', function (Request $request, string $id) {
    Gate::authorize('edit-forms');
    $definition = json_decode($request->getContent(), flags: JSON_THROW_ON_ERROR);   // the raw body keeps {} as {} (see Load and Save Form JSON Schemas)
    $lint = SurveyJsService::post('/schema', $definition, timeout: 10);
    if ($lint->status() === 422 && $lint->json('errors') !== null) {           // errors: refuse the save, report them as they are
        return response($lint->body(), 422)->header('Content-Type', 'application/json');
    }
    $warningsOnly = $lint->status() === 200 && array_keys((array) $lint->json()) === ['warnings'];
    if (! $warningsOnly && ($lint->status() !== 200 || $lint->body() !== '{}')) {   // fail closed: nothing else counts as clean
        SurveyJsService::unexpected('/schema', $lint);
    }
    StoredJson::put('forms', $id, $definition);                                 // stored as it arrived: 1.0 stays 1.0

    return $warningsOnly ? response()->json(['warnings' => $lint->object()->warnings]) : response()->noContent();   // warnings don't block the save
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/lint-definition.php#L14-L29 --->

</details>

[Live Example: Lint JSON Schemas](https://surveyjs-php.demos.surveyjs.io/examples/lint-definition (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Generate PDFs --->

### Generate PDFs

A backend workflow may need a PDF for an archive or email attachment. [SurveyJS PDF Generator](/pdf-generator/documentation/overview) can create the document on the server without opening a browser.

Load the form JSON schema and, for a completed form, its saved answers. Pass them to PDF Generator to create the document. Your backend can then store the PDF, attach it to an email, or send it to the browser with the `application/pdf` content type.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Generate PDFs --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/server-pdf.js#L24-L41 --->

```js
// Open a tab during the click and navigate only after the server returns a PDF
async function generatePdf(id, action) {
  if (urls.has(id)) return usePdfUrl(id, action, urls.get(id));
  const tab = action === "open" ? window.open("/examples/server-pdf/loading", "_blank") : null;
  try {
    const response = await fetch(`/api/claims/${id}/pdf`);
    if (!response.ok) throw await responseError(response, "Couldn't generate the PDF. Please try again.");
    if (!response.headers.get("content-type")?.startsWith("application/pdf")) throw new Error("The server didn't return a PDF. Please try again.");
    const blob = await response.blob();
    if (!blob.size) throw new Error("The server returned an empty PDF. Please try again.");
    const url = URL.createObjectURL(blob);
    urls.set(id, url);
    if (action === "download") return usePdfUrl(id, action, url);
    const opened = tab && !tab.closed;
    if (opened) tab.location = url;
    return { message: opened ? "PDF opened in a new tab." : "PDF ready. Select Open PDF again or Download PDF.", needsAction: !opened };
  } catch (error) { tab?.close(); throw error; }
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/server-pdf.js#L24-L41 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/server-pdf.php#L10-L29 --->

```php
// GET /api/claims/{id}/pdf — ask the SurveyJS service for the filled form and pass the PDF through
Route::get('/api/claims/{id}/pdf', function (string $id) {
    $claim = DB::table('responses')->where('form_id', 'claim')->where('id', $id)->first() ?? abort(404, 'Unknown claim');
    // Use the schema version recorded with the response
    $definition = match ($claim->definition_version) {
        'v1', 'v2' => file_get_contents(base_path("shared/definitions/relational-storage.{$claim->definition_version}.json")),
        null => DB::table('forms')->where('key', 'claim')->value('json'),
        default => abort(409, 'The schema version for this claim is unavailable'),
    };
    $pdf = SurveyJsService::post('/pdf', ['schema' => json_decode($definition), 'response' => json_decode($claim->data)], timeout: 60);
    if ($pdf->status() !== 200 || ! str_starts_with($pdf->header('Content-Type'), 'application/pdf') || ! str_starts_with($pdf->body(), '%PDF-')) {
        SurveyJsService::unexpected('/pdf', $pdf);
    }

    return response($pdf->body(), 200, [
        'Content-Type' => 'application/pdf',
        'Content-Disposition' => "inline; filename=\"claim-{$id}.pdf\"",
        'Cache-Control' => 'private, no-store',
    ]);
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/server-pdf.php#L10-L29 --->

</details>

[Live Example: Generate PDFs](https://surveyjs-php.demos.surveyjs.io/examples/server-pdf (linkStyle))

<!--- @@inject: ../DocsShared/backend-integration-common.md#heading=Extract Responses from Documents --->

### Extract Responses from Documents

Some responses arrive as completed paper forms, scans, or PDFs. [AI Form Response Extractor](/documentation/combine-paper-and-online-survey-form-data) can use your form JSON schema to read those documents and return answers in the same format as an online response.

Upload the document to your backend and send it, along with the JSON schema, to the extractor. The extractor calls the AI provider you configure and returns the answers with confidence information. It can also return a unique ID detected in the document, such as an ID from a QR code.

Use the returned answers to fill a draft form. Show which answers need checking so a person can review and correct them before submitting. Extraction itself does not save a response—save the reviewed answers through your usual endpoint.

<!--- @@inject-end: ../DocsShared/backend-integration-common.md#heading=Extract Responses from Documents --->

<details>
  <summary>Client code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/extract-from-paper.js#L57-L68 --->

```js
// Extract a draft without saving it and validate the response before replacing any answers
async function extract(file, signal) {
  const body = new FormData();
  body.append("scan", file);
  const response = await fetch("/api/work-orders/extract", { method: "POST", body, signal });
  if (!response.ok) throw await responseError(response, "Couldn't extract the answers. Try again or enter the answers directly in the form.");
  const result = await response.json();
  if (!result.answers || typeof result.answers !== "object" || Array.isArray(result.answers) || !Array.isArray(result.confidence)) {
    throw new Error("The extraction result couldn't be read. Try again or enter the answers directly in the form.");
  }
  return result;
}
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/shared/client/extract-from-paper.js#L57-L68 --->

</details>

<details>
  <summary>Server code</summary>

<!--- @@inject: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/extract-from-paper.php#L31-L48 --->

```php
// POST /api/work-orders/extract — send the uploaded scan to the SurveyJS service; return a draft response
Route::post('/api/work-orders/extract', function (Request $request) {
    $scan = $request->file('scan') ?? abort(400, 'Upload the scan in a field named "scan"');
    abort_if(! $scan instanceof UploadedFile || ! $scan->isValid() || $scan->getSize() > 5 * 1024 * 1024, 413, 'The scan must be a file of 5 MB or less');
    abort_unless(in_array($scan->getMimeType(), ['application/pdf', 'image/png', 'image/jpeg', 'image/webp', 'image/gif'], true), 400, 'The file is not a PDF, PNG, JPEG, WebP or GIF document');
    $out = SurveyJsService::post('/extract', [                                  // JSON with base64, not multipart
        'schema' => json_decode(DB::table('forms')->where('key', 'work-order')->value('json')), 'document' => base64_encode($scan->get())], timeout: 120);
    $result = $out->object();

    return match (true) {                                                       // nothing is saved: a person reviews the draft
        $out->status() === 200 && is_object($result) && is_object($result->data ?? null) => response()->json(
            ['answers' => $result->data, 'confidence' => $result->confidence ?? [], 'uniqueId' => $result->uniqueId ?? null]),
        $out->status() === 400 && $out->json('error') === 'INVALID_DOCUMENT' => response()->json(['error' => 'The file is not a PDF, PNG, JPEG, WebP or GIF document'], 400),
        $out->status() === 503 && $out->json('error') === 'AI_NOT_CONFIGURED' => response()->json(['error' => 'The SurveyJS service has no AI provider configured'], 503),
        $out->status() === 502 && $out->json('error') === 'EXTRACTION_FAILED' => response()->json(['error' => 'Could not extract the response from the document'], 502),
        default => SurveyJsService::unexpected('/extract', $out, logBody: false),
    };
});
```

<!--- @@inject-end: https://github.com/surveyjs/surveyjs-php-laravel/blob/e8b2d3eed03092a53e7f99714d0f8f6de8d43a43/routes/examples/extract-from-paper.php#L31-L48 --->

</details>

[Live Example: Extract Responses from Documents](https://surveyjs-php.demos.surveyjs.io/examples/extract-from-paper (linkStyle))
