Build a complete Field Notes plugin
Build a private notebook for a signed-in player. A player can create, list, edit and delete their own notes. Creating a note fires a custom Pulse hook that adds a local notification. The feature has its own table and Vue screen, and can be disabled without deleting data.
This exercise connects the plugin lifecycle, HTTP contracts, data ownership, hooks, frontend runtime and packaging. No gameplay package, money system, external email or remote service is required.
The complete example lives in docs/examples/field-notes in this repository. It is deliberately outside installed plugin discovery. Use a disposable local Pulse installation for the installation steps; the test commands below keep their database in memory and never install the example into your current game.
What you will learn
| Piece | Responsibility |
|---|---|
plugin.json |
Stable slug, namespace, version, routes and runtime descriptor |
FieldNotesPlugin.php |
Extends Pulse's base Plugin; inherits hook registration |
database/migrations/...create_field_notes_table.php |
Plugin-owned schema, index and user-deletion rule |
Models/FieldNote.php |
Assignment rules and owner relation |
Controllers/FieldNotesController.php |
Validation, owner-scoped queries and JSON responses |
routes/api.php |
Real endpoints plus authentication, ban and package guards |
hooks.php |
Optional local response to the feature's custom event |
frontend/src/FieldNotesView.vue |
Loading, empty, success, validation/network error and editing states |
build.mjs |
Compiles Vue into the current Pulse runtime format and computes SRI |
tests/ |
Isolated real HTTP tests and a mocked-host browser exercise |
upgrades/ |
An additive schema-upgrade exercise, separate from version 1.0 migrations |
The backend trusts the authenticated account, not a user_id supplied by the browser. The browser's requiresAuth metadata improves navigation; middleware and owner-scoped queries protect the API.
1. Read the manifest and file placement
The example uses slug field-notes, namespace App\Plugins\FieldNotes and class App\Plugins\FieldNotes\FieldNotesPlugin. These are related identifiers with different spelling: the slug belongs in URLs/registry rows; the namespace belongs in PHP imports. The folder is backend/app/Plugins/field-notes when you intentionally install it.
Relevant manifest fields:
{
"name":"Field Notes",
"slug":"field-notes",
"namespace":"App\\Plugins\\FieldNotes",
"class":"App\\Plugins\\FieldNotes\\FieldNotesPlugin",
"version":"1.0.0",
"enabled":false,
"license_required":false,
"routes":{"api":true,"web":false,"admin":false},
"frontend":{
"slots":{},
"routes":[{
"path":"/field-notes",
"name":"field-notes.home",
"component":"FieldNotesView.vue",
"meta":{"title":"Field Notes","requiresAuth":true}
}]
}
}
The actual manifest also contains description, author, dependency and settings fields. It starts disabled. An existing installation's installed_plugins.enabled controls runtime state after registration; changing a JSON boolean is not the enable command. No menu is declared, so use the frontend route directly. Adding a menu is a separate navigation contract. For adding administrative views and moderation tables, see Building plugin admin views.
The base Plugin class is constructed with the package directory. It loads the manifest and inherits boot()/registerHooks(). The hook loader tracks canonical paths per application container to avoid loading the same file twice. Do not add a second unconditional require hooks.php in production boot code.
2. Give notes their own table
The initial migration creates field_notes with:
| Column / key | Purpose |
|---|---|
id |
Integer primary key |
user_id |
Required FK to core users.id, cascade on physical user deletion |
title |
String, maximum declared length 120 |
body |
Text; API validation limits it to 2,000 characters |
created_at, updated_at |
Standard timestamps |
Index (user_id,id) |
Supports owner lookup and recent-ID ordering |
The model's fillable fields are user_id,title,body and user() belongs to core User. Fillable is a mass-assignment rule, not authorization. The controller must still set the owner itself. Core remains independent of this concrete plugin class.
No columns are added to users. The migration's down() drops only field_notes; rolling it back destroys the notes. Disabling the plugin does not run that rollback. SQLite tests confirm their configured cascade, but do not establish MariaDB lengths, collation or concurrent behavior.
3. Mount guarded routes
routes/api.php declares four endpoints. PluginServiceProvider normally mounts it under /api/plugins/field-notes with the API, Sanctum and plugin-access middleware. The file repeats the account/package guards explicitly and adds the banned-user guard, so manual test mounting preserves the intended boundary.
use App\Plugins\FieldNotes\Controllers\FieldNotesController;
use Illuminate\Support\Facades\Route;
Route::middleware(['auth:sanctum', 'user.banned', 'plugin.access:field-notes'])
->group(function (): void {
Route::get('notes', [FieldNotesController::class, 'index']);
Route::post('notes', [FieldNotesController::class, 'store']);
Route::patch('notes/{note}', [FieldNotesController::class, 'update'])->whereNumber('note');
Route::delete('notes/{note}', [FieldNotesController::class, 'destroy'])->whereNumber('note');
});
Expected boundaries: guest 401; package absent 404 with plugin_not_installed; disabled package 403 with plugin_disabled; another account's note ID 404. The host can also stop a request for IP ban, uninstalled state or suspended account. See shared HTTP behaviour.
The provider may register legacy aliases as well. Use the canonical URL above in new clients. Do not declare the API public to make an authentication problem disappear.
4. Validate and scope every operation
Both create and edit require title (string, maximum 120) and body (string, maximum 2,000). Edit replaces both fields; this example does not implement a sparse PATCH. Other JSON keys are ignored because the controller builds the accepted array explicitly.
Create assigns user_id from $request->user()->id. Update/delete first query where('user_id', currentId)->findOrFail(noteId). Consequently, guessing a valid ID belonging to another player yields the same 404 as an absent row. The listing applies that scope too, sorts by descending ID and returns the newest 50; it is not a paginator.
| Request | Response |
|---|---|
GET /api/plugins/field-notes/notes |
200, {"data":[...]}; empty is {"data":[]} |
POST /api/plugins/field-notes/notes |
201, {"data":<saved note>} |
PATCH /api/plugins/field-notes/notes/{note} |
200, {"data":<updated note>} |
DELETE /api/plugins/field-notes/notes/{note} |
204, no body |
| Invalid create/edit | 422, Laravel message,errors; no accepted-field update |
| Absent/other-owner note | 404; no update/delete |
Example JSON body:
{"title":"Northern gate","body":"Bring a lantern."}
With a valid local token and enabled package, POST returns your saved record with ID, owner ID and timestamps. A subsequent GET includes it. Sending somebody else's user_id in that body cannot select the owner. The API returns plain stored text; Vue interpolation displays it as text rather than HTML.
Create has no request idempotency key. Repeating it can create another note. The UI disables duplicate submissions while busy, but that is not a durable retry guarantee. Add an explicit client request key and unique schema rule if your feature needs once-only creation.
5. Fire an event you actually own
After saving, the controller dispatches:
app('hook')->action('field-notes.created', ['note' => $note, 'user' => $request->user()]);
The plugin's hooks.php listens to this exact name. It checks the package is still enabled, verifies that the payload contains a FieldNote and core User with matching ownership, then calls NotificationService::system for that user. That service writes a local notification; it does not send email or guarantee live transport delivery.
The enabled check also protects an already loaded callback in a long-running process after the database state changes. It does not replace the route guard. HookService catches listener exceptions; a failed notification can leave a successfully saved note. The example intentionally treats this notification as optional, without one transaction around both writes. Required accounting/invariants need a different design.
field-notes.created is supplied by this plugin, not a new core lifecycle promise. It is absent from the core hook count. Test the real POST and notification effect, not just the fact that a callback registered.
6. Build the player screen
The supplied Vue SFC has labelled title/body controls, create/edit/delete actions, busy buttons, role="status" success/loading text and role="alert" errors. It renders explicit empty and failed-load states. Delete is immediate in this small exercise; add a confirmation/undo contract if your product needs one.
It uses window.LFStudioPluginRuntime.http, the host's authenticated API bridge, rather than reading a token itself. An absolute same-origin URL avoids doubling a client's /api/v1 base prefix. The GET includes a unique query value because the current host bridge has no force-refresh argument and its underlying API client caches GETs; this bypasses stale reads after changes. It also creates distinct short-lived cache entries, so it is a teaching workaround rather than a general cache design. See API caching.
The runtime registers component key FieldNotesView.vue, matching the manifest exactly. It shares the host Vue object; a second bundled Vue runtime would break integration assumptions. The build creates frontend/dist/plugin.js and plugin.css, and writes SHA-384 SRI values under frontend.runtime in the fixture manifest.
From the Pulse repository root, with frontend dependencies installed:
node docs/examples/field-notes/build.mjs frontend
This fixture builder writes only inside its own directory. It does not publish assets or register the package. Generated frontend/dist is ignored by Git; run the build before validating or packaging a fresh checkout. It uses the host's installed Vite/Vue toolchain, not a separate lockfile.
The official frontend/scripts/build-plugin-runtime.mjs also publishes into host public directories. The current PHP compileRuntimeBundle helper instead produces placeholder render functions, without compiling this Vue logic. For this example, preserve the working Vite output and use pulse:package --skip-build later.
7. Execute the isolated tests first
The supplied test bootstrap forces testing, SQLite :memory:, array cache/session/mail and disabled pulse. It bypasses cached host configuration. Its HTTP tests manually mount only the example's routes, apply core migrations plus this example's initial migration, block stray HTTP requests and fake email. They skip the installed-marker middleware without creating/removing your host's marker. Real authentication/package middleware and owner queries remain enabled.
From the repository root using the development container:
docker compose cp docs/examples/field-notes backend:/tmp/pulse-field-notes
docker compose exec -e PULSE_TEST_BACKEND=/var/www/html backend /var/www/html/vendor/bin/phpunit -c /tmp/pulse-field-notes/phpunit.xml
The tests cover guest rejection, empty state, invalid input, forced authenticated ownership, local notification, owner-scoped newest-50 listing, cross-account edit/delete denial, owner edit/delete, missing/disabled package access, retained-hook behavior, additive upgrade preservation and user-deletion cascade. The test database disappears with the PHP process. Do not change its database settings to your game database.
The browser exercise runs the built SFC in a small mocked runtime host, so it checks UI behavior without logging into or installing in the real game:
node docs/examples/field-notes/tests/browser.mjs frontend
That command requires the host's installed Playwright/Chromium. It checks desktop/mobile states, interactions, long text, keyboard focus and integrity metadata, and writes evidence under the OS temporary directory. It does not establish integration with a real login, loader, installed registry or server. Test those separately in the practice installation below.
8. Install intentionally in a practice game
Use a disposable local Pulse host with a working account, core migrations, frontend dependencies and database backup. Copy the built example directory into its backend/app/Plugins/field-notes. Do not overwrite an existing package of that slug. Keep its namespace/class names unchanged.
From that practice backend (prefix PHP commands with docker compose exec backend, run from that host's repository root, only when it is a local Docker Compose install):
php artisan hub:validate field-notes
Validation must succeed. You do not need to migrate by hand: hub:enable (below) runs the package's pending migrations from its own folder before it marks the plugin enabled, and a failed migration leaves it disabled with the error shown. Inspect the schema afterwards rather than treating the enable message as proof the table you expect exists. Migrations change the selected database; these installation commands are intentionally separate from the isolated tests.
Register this one package through the current admin registration interface, or in the practice backend's Tinker:
$result = app(\App\Core\Services\PluginManagerService::class)->registerPlugin('field-notes');
dump($result);
Check success and messages. Registration validates/publishes runtime files, stores the descriptor and clears manifest cache; it does not make the source folder alone active. Then enable it:
php artisan hub:enable field-notes
Refresh the player application so it reloads its registry, then visit /field-notes. Inspect /api/plugins/enabled/field-notes for the exact runtime entry/style URLs and matching component route metadata. Confirm those assets load with integrity checks. Create a note, reload, edit, delete and verify the local notification. Use two accounts to confirm each gets a separate list and cannot edit the other's ID.
Disable using php artisan hub:disable field-notes; a fresh application should omit its manifest and the API should reject access. The table and notes remain. Re-enable and verify data returns. Restart/recycle a long-running local worker when testing boot/discovery changes; previously loaded routes/callbacks do not automatically unload from an existing process.
This installation/real-login workflow is an acceptance exercise to perform on your host; the isolated checks reported above do not claim it was completed for every environment.
9. Package the compiled feature
In that practice host, after build, validation and interaction checks:
php artisan pulse:package field-notes --type=plugin --skip-build --output=storage/app/packages
--skip-build preserves the compiled Vue output; it does not mean no filesystem writes. Inspect the ZIP for manifest, PHP, migration, compiled JS/CSS and matching SRI. Packaging creates an archive; it does not sign, upload, publish a listing or prove installation on another host. Use the package guide and command contract for current signing/validation/install behavior.
Keep a clean source package without PHPUnit caches, local tokens, .env, test databases or node_modules. Install the ZIP into a second disposable host and repeat enable/disable and account isolation before distributing it. This is separate from building the fixture in place.
10. Prepare an upgrade without losing notes
The example includes upgrades/2026_10_24_200000_add_is_pinned_to_field_notes.php outside the active migration directory. It adds is_pinned with default false. The isolated test applies it to existing data and checks the old note remains.
To prepare a real version 1.1.0 exercise:
- Copy that file into the package's
database/migrations; leave the original create migration unchanged. - Add
is_pinnedboolean casting/allowed assignment and an explicitly validated API/UI operation if you want pinning behavior. A column alone does not implement it. - Change manifest version to
1.1.0, build again and regenerate SRI for the new artifact. - Back up a practice host containing version 1.0 notes, apply the reviewed additive migration, refresh registry/runtime metadata using the supported package update flow and verify old/new data plus disable/re-enable.
- Test the ZIP update on a second host. Check schema/registry/runtime version and errors independently: file replacement and database migration are not one universally atomic rollback.
Rollback of this additive migration drops only is_pinned; rolling back the original create migration destroys every note. Restoring old PHP/JS does not undo data changes. Document compatibility and recovery for each actual release rather than assuming the generic upgrade() callback supplies migrations or automatic backup.
Read the complete source
Example directory (docs/examples/field-notes) contains every file discussed here. Controller (docs/examples/field-notes/Controllers/FieldNotesController.php), Vue view (docs/examples/field-notes/frontend/src/FieldNotesView.vue) and HTTP tests (docs/examples/field-notes/tests/FieldNotesTest.php) are the main reading points. These links use the repository branch; local edits become visible on GitHub only after a push.