Search by

sp4cecat / kodex-laravel-editor

sp4cecat

Laravel integration for Kodex Editor, a rich text editor: HTML sanitiser, uploads, content renderer, PDF export, Filament field, Laravel Nova field and tool, and Inertia helper.

Package info

github.com/sp4cecat/kodex-laravel-editor

pkg:composer/sp4cecat/kodex-laravel-editor

Statistics

Installs: 2

Dependents: 0

Suggesters: 0

Stars: 0

Open Issues: 0

v0.1.0 2026-12-02 13:53 UTC

This package is auto-updated.

Last update: 2026-12-02 13:58:30 UTC


README

The Laravel side of the Kodex rich text editor:

  • a sanitiser that reduces any HTML to the Kodex content format;
  • an Eloquent cast and a validation rule built on it;
  • a Blade component that renders saved content with the stylesheets and web fonts it needs;
  • an upload route that trusts nothing the browser says;
  • a web-font catalogue route and a PDF export route;
  • a Filament form field;
  • a Laravel Nova field and a Documents tool;
  • a helper that hands the editor's configuration to Inertia pages (Vue or React).

Requires PHP 8.3+ and Laravel 12 or 13. It is developed and tested on PHP 8.4 with Laravel 13, Filament 5 (Livewire 4) and Inertia 3. The Filament field only uses APIs that Filament 4 also has, and the composer constraints allow Laravel 12 and Filament 4, but those combinations have not been run.

Install

composer require sp4cecat/kodex-laravel-editor
php artisan kodex:install

kodex:install publishes config/kodex.php and the package's public files (public/vendor/kodex), runs filament:assets when Filament is installed, and prints the next steps. Run it again after updating the package. The individual publish tags are kodex-config, kodex-assets and kodex-views.

Uploads go to the public disk by default, so that disk needs its symlink: php artisan storage:link.

Configure

Everything is in config/kodex.php, with a comment on each setting. The three you will want first:

// The public stylesheets of the site the content appears on: URLs or Vite entry points.
// The editor loads them into its editing area, so content looks the same while it is written.
'content_css' => ['resources/css/site.css'],

// Class names content may carry (your named styles). Every other class is removed.
'sanitizer' => ['allowed_classes' => ['lead', 'badge'], /* … */],

// Who may upload, list fonts and export PDFs. Signed-in users by default.
'routes' => ['prefix' => 'kodex', 'middleware' => ['web', 'auth']],

A Vite entry in content_css is resolved through the Vite manifest, so it needs npm run build (or the dev server).

Keep page furniture out of the way in that stylesheet: what it says about body, headings and plain elements is what the editor shows. Rules for your header, navigation and so on are best scoped under their own classes.

Saving content

Cast the column. Content is sanitised every time it is assigned, whatever assigns it:

use Kodex\Editor\Casts\KodexHtml;

class Post extends Model
{
    protected function casts(): array
    {
        return ['body' => KodexHtml::class];
    }
}

Reading the attribute gives a plain string, the HTML as stored. It is not an Htmlable object: {{ $post->body }} still escapes it. Rows written around the model (query builder, imports, older data) are not sanitised by the cast.

Validate before saving:

use Kodex\Editor\Rules\KodexContent;

$request->validate([
    'body' => ['required', new KodexContent],                 // not longer than the sanitiser accepts
    'body' => ['required', (new KodexContent)->max(200_000)], // your own limit, in bytes
    'body' => ['required', (new KodexContent)->unchanged()],  // also refuse anything the sanitiser would alter
]);

The length check is worth having even when you do not use unchanged(): content longer than sanitizer.max_input_length makes the sanitiser throw Kodex\Editor\Exceptions\ContentTooLong (it never cuts content), and a validation message is the better way to hear about it.

To sanitise by hand: app(\Kodex\Editor\Sanitizer\Sanitizer::class)->sanitize($html) or kodex_sanitize($html).

Showing content

<x-kodex::content :html="$post->body" />

This wraps the content in <div class="kodex-content"> (extra attributes such as class and id are passed on), sanitises it, and makes sure two things are on the page, once each however many times the component is used:

  • the Kodex content stylesheet (figures, crops, table presets, check lists, embeds) — a <link> to public/vendor/kodex/content.css when it has been published, otherwise the same CSS inline;
  • a stylesheet <link> for every web font the content uses that the font provider's catalogue knows.

Pass clean to skip sanitising when you know the value is already clean: <x-kodex::content :html="$post->body" clean />.

Where the <link> tags go is render.styles in the config:

Value Where
inline (default) right before the first piece of content on the page; works with any layout
stack pushed onto the Blade stack named in render.stack, for layouts with @stack('styles') in the head
manual nowhere: put @kodexStyles in your layout's <head>

@kodexStyles works because Blade renders a layout after the content it wraps, so by then the fonts are known.

Your own site stylesheet is not added by the component; your layout already loads it.

Filament

use Kodex\Editor\Filament\KodexEditor;

KodexEditor::make('body')
    ->contentCss([Vite::asset('resources/css/site.css')])   // default: config content_css
    ->directory('posts')

The field's state is the HTML string. It is sanitised when the form is saved, so it is safe in places a cast cannot reach, such as inside a Repeater stored as JSON. Content that is too long is a validation error.

Method
toolbar(string|false) layout such as 'undo redo | bold italic'; false hides it
menubar(bool|string) on, off, or the menus to show
statusbar(bool)
contentCss(array) stylesheets for the editing area (URLs or Vite entries)
bodyClass(string) class for the content body, for example prose
mode('frame'|'inline') isolated editing area that loads contentCss, or in-page editing
height(int|'auto'), minHeight(int), maxHeight(?int) pixels; maxHeight(null) removes the limit
disk(string), directory(string) where uploads go
maxUploadSize(int $kb), acceptedFileTypes(array) upload limits (image types only; never SVG)
uploads(false) no uploads from this field
collapsedSelectionScope('block'|'caret') what formatting applies to when nothing is selected
fontSizeUnit('px'|'pt'|'rem'|'em'|'%')
placeholder(string), documentTitle(string)
editorOptions(array) any other editor option, by its JavaScript name; applied last

All of them accept closures, like other Filament fields. Defaults for every form come from the editor section of the config.

The editor's script and stylesheet are registered with Filament and loaded only on pages that show the field. php artisan filament:assets (run by kodex:install) publishes them.

Laravel Nova

Nova is optional. When it is installed, the package offers a field for resource forms and a tool page. Both load the editor only on pages that show it: Nova itself loads a 23 kB script that registers the components, and the editor is fetched from the package's own asset route (/kodex/assets/…) when a form opens. Nothing needs publishing.

Field

use Kodex\Editor\Nova\KodexEditor;

public function fields(NovaRequest $request): array
{
    return [
        Text::make('Title'),

        KodexEditor::make('Body')
            ->contentCss(['resources/css/site.css'])   // the public site's stylesheet (URL or Vite entry)
            ->directory('posts')                        // where dropped and pasted pictures are stored
            ->alwaysShow(),                             // show the content on the detail page without a click
    ];
}
  • The value is the editor's HTML. It is sanitised when the resource is saved, whether or not the model also uses the KodexHtml cast.
  • The detail page shows the content in a script-less frame with the site's stylesheet, so it looks as it will when published. The field is hidden from index tables by default; ->showOnIndex() shows a short plain-text excerpt.
  • Options: toolbar(), menubar(), contentCss(), bodyClass(), mode(), height(), minHeight(), maxHeight(), disk(), directory(), maxUploadSize(), acceptedFileTypes(), withoutUploads(), collapsedSelectionScope(), fontSizeUnit(), editorOptions([...]), plus Nova's own rules(), help(), readonly(), dependsOn(), placeholder().
  • The editor follows Nova's light and dark themes and takes Nova's primary colour.

Pictures are uploaded through the package's upload route, which uses the routes.middleware setting in config/kodex.php (web and auth by default). If Nova signs users in with a guard other than the default one, set that middleware to match (for example ['web', 'auth:admin']).

Tool: Documents

A "Documents" page in Nova's sidebar for free-standing content written in the editor (terms, an about page, snippets), stored in a kodex_documents table.

php artisan vendor:publish --tag=kodex-documents-migration
php artisan migrate
// app/Providers/NovaServiceProvider.php
use Kodex\Editor\Nova\KodexDocuments;

public function tools(): array
{
    return [
        KodexDocuments::make()
            ->editorOptions(['contentCss' => ['resources/css/site.css']]),
        // ->label('Pages')->icon('document-text')->canSee(fn ($request) => $request->user()->isAdmin())
    ];
}

Each document has a title, a slug and a body. Fetch one by its slug wherever you need it:

<x-kodex::content :html="\Kodex\Editor\Documents\Document::html('terms')" />

The page lists documents, opens one in the editor (with Word import and export from the File menu), and asks before deleting or before leaving unsaved changes. Its API lives under nova-vendor/kodex-documents, behind Nova's own sign-in and the tool's canSee rule, and sanitises what it stores.

Inertia (Vue or React)

Give the page the editor's configuration from the controller:

use Kodex\Editor\Kodex;

return Inertia::render('Posts/Edit', [
    'post' => $post->only('id', 'title', 'body'),
    'kodex' => Kodex::config([
        'documentTitle' => $post->title,
        'upload' => ['directory' => 'posts'],   // 'disk', 'maxSize' (KB), 'accept'; or false for no uploads
    ]),
]);

Kodex::config() returns the same object the Filament field uses: the editor options from the config and your overrides, the site's stylesheets, a freshly issued upload policy, and the font and PDF routes.

Add the package's Vite plugin, which provides the @kodex/* imports:

// vite.config.js
import kodex from './vendor/sp4cecat/kodex-laravel-editor/vite-plugin.js';

export default defineConfig({
    plugins: [laravel({ /* … */ }), vue() /* or react() */, kodex()],
});

Vue:

<script setup>
import { useForm } from '@inertiajs/vue3';
import { KodexEditor } from '@kodex/vue';
import '@kodex/style.css';

const props = defineProps({ post: Object, kodex: Object });
const form = useForm({ title: props.post.title, body: props.post.body ?? '' });
</script>

<template>
    <KodexEditor v-model="form.body" :config="kodex" />
</template>

React:

import { useForm } from '@inertiajs/react';
import { KodexEditor } from '@kodex/react';
import '@kodex/style.css';

export default function Edit({ post, kodex }) {
    const { data, setData } = useForm({ title: post.title, body: post.body ?? '' });

    return <KodexEditor value={data.body} onChange={(html) => setData('body', html)} config={kodex} />;
}

The editor's own requests (uploads, fonts, PDF) send the CSRF token from <meta name="csrf-token"> or the XSRF-TOKEN cookie, so the root view needs one of them, as Inertia apps normally have.

Save through a controller that validates with KodexContent and a model that casts with KodexHtml.

Sanitising, and why it matters

The editor only produces the content format, but the server cannot know that a request came from the editor. Anyone who can submit the form can submit any HTML. So the server reduces whatever arrives to the format, every time, and treats the editor's own filtering as a convenience.

What the sanitiser does:

  • Allow-list, not block-list. Elements, attributes, CSS properties and their value types come from one file, resources/schema-manifest.json. What is not listed is removed. The file is plain data, so the editor's JavaScript schema can be checked against it too.
  • Styles are rebuilt, never copied. A style attribute is parsed into typed values (colour, length, keyword, font list, ratio, border) and written out again from those values. Only the properties the format allows on that element survive; sizes are clamped; anything containing url(, var(, expression(, \, @, comments or !important is dropped. There is no position, z-index or display, so content cannot draw over your page.
  • Derived values are recomputed. A crop's styles are calculated from data-crop and the picture's size; a figure's float follows data-wrap; a table's margins follow data-align; rel="noopener noreferrer" is present exactly when target="_blank" is. What arrived for these is ignored.
  • URLs may be http, https, mailto, tel, relative or #fragment for links, and http, https or relative for pictures and media. data: images are kept only if you turn allow_data_images on, and only PNG, JPEG, GIF, WebP and AVIF.
  • Embeds are iframes on the embed_hosts you list, over https, inside the embed wrapper, with no srcdoc, sandbox, allow or name.
  • Anchor ids must fit a pattern and must not be names that would shadow properties of window or document (location, forms, config, …). Set anchor_id_prefix if ids could collide with your own; links to #fragment targets get the same prefix.
  • Classes are limited to allowed_classes.
  • No comments, no script/style/svg/math, no forms, no event handlers, no id or name anywhere else.

It always returns a string. The one exception it throws is ContentTooLong, because cutting a document at a length limit would silently lose the end of it.

It is built on symfony/html-sanitizer. The package's own pass runs on the parsed tree before that library writes the result, so there is one parse and one serialisation, and the output is never edited as text. On PHP 8.4+ the HTML is parsed by PHP's built-in HTML5 parser; on PHP 8.3 by masterminds/html5, which symfony/html-sanitizer 7.4 brings with it. (The test suite runs the content and attack corpora through both parsers, but on PHP 8.4.)

The output spells a few characters as numeric entities (= as &#61;, +, @, backtick and " likewise). That is the library's doing; it is the same content. Compare content with Sanitizer::isClean() or the unchanged() rule rather than with ===.

Uploads and the signed policy

POST /kodex/uploads stores an image and answers { "url": "…", "width": n, "height": n }.

The browser does not get to say where a file goes or what is allowed. When the server builds the editor's configuration it issues an upload policy: the disk, folder, size limit, accepted types, an expiry time and the id of the signed-in user, encrypted and authenticated with your APP_KEY. The editor sends the policy back with each file; the route reads everything from it and ignores anything else in the request. A missing, altered, expired or borrowed policy is a 403.

use Kodex\Editor\Uploads\UploadPolicy;

$policy = UploadPolicy::issue(disk: 'public', directory: 'posts', maxKb: 2048, mimes: ['image/png'], ttl: 60);

The file itself is checked by its content, not its name or the type the browser claimed:

  • its detected type must be one of JPEG, PNG, GIF, WebP or AVIF, and one the policy lists. SVG is never accepted, even if a policy lists it, because an SVG file can carry scripts;
  • its image header must agree with that type and give a size within uploads.max_dimension;
  • it must not contain markup or PHP tags anywhere (<?php, <script, <html, …), which is how a file that is both an image and something else is refused;
  • it is stored under a random name with the extension of the detected type.

The route is throttled (uploads.throttle) and, by default, needs a signed-in user. Errors come back as Laravel's usual 422 JSON, which the editor shows.

Not done: image metadata (EXIF, including location) is left as it is, and images are not re-encoded.

A policy lasts uploads.policy_ttl minutes (12 hours by default). Someone who keeps a form open longer has to reload it before uploading again.

Web fonts

GET /kodex/fonts gives the editor the provider's family list as [{ "family": "…", "category": "…", "variants": ["400", "400i", …] }]. Your server fetches and caches it (fonts.cache_ttl), and the content component uses the same cached list to decide which font stylesheets a page needs.

  • bunny (default): fonts.bunny.net. No key.
  • google: needs services.google_fonts.key for the list. Without a key the list is empty.
  • null: no web fonts.

app(\Kodex\Editor\Fonts\FontCatalogue::class)->stylesheetUrl('Playfair Display') returns the stylesheet URL for a family (regular, italic, bold and bold italic, or the variants you pass).

If the provider cannot be reached while a page is being rendered, the page is rendered without the font links and the provider is not asked again for five minutes.

PDF export

POST /kodex/pdf with html and title answers with a PDF download. The driver is pdf.driver in the config (KODEX_PDF_DRIVER):

Driver Needs Result
null (default) nothing The route answers 501 with a JSON message and the editor uses the browser's print dialog.
chrome composer require spatie/laravel-pdf chrome-php/chrome and a Chrome or Chromium binary on the server (no Node) What the browser shows: your stylesheets, web fonts, crops, floats, page breaks.
dompdf composer require dompdf/dompdf Basic. dompdf understands a subset of CSS 2.1: no web fonts, no crops (pictures are shown whole), embeds and videos become links, collapsible sections are shown open. Stylesheets that rely on custom properties, flexbox or grid will not look the same.

Set pdf.chrome.binary (KODEX_CHROME_BINARY) if Chrome is not found on its own, and KODEX_CHROME_NO_SANDBOX=true where Chrome cannot use its sandbox (some containers).

Both drivers are locked down the same way:

  • only the sanitiser's output is rendered, inside a document the package builds;
  • scripts are off (Chrome: script execution is disabled in the browser and the document's Content Security Policy says script-src 'none'; dompdf: its JavaScript and embedded-PHP features are off);
  • the renderer may fetch only from your APP_URL, the hosts of your content_css, the font provider, and the hosts in pdf.allowed_hosts (Chrome: the Content Security Policy plus a host-resolver rule; dompdf: its allowed-hosts list);
  • no local files (dompdf is confined to an empty folder and the file:// protocol is off).

Two consequences:

  • pictures served from another host (a CDN, S3) appear in the PDF only if that host is in pdf.allowed_hosts;
  • with chrome, the browser asks your application for the stylesheets and pictures while the export request is still open. A server that handles one request at a time cannot answer both and the export times out. php artisan serve is such a server unless you start it as PHP_CLI_SERVER_WORKERS=4 php artisan serve --no-reload.

To use another renderer, implement Kodex\Editor\Pdf\PdfRenderer and register it: app(\Kodex\Editor\Pdf\PdfManager::class)->extend('name', fn ($app) => new YourRenderer).

Security notes

  • Leave auth (or your own equivalent) on the package routes. Without it anyone can store files on your disk and make your server fetch font lists and render PDFs.
  • Sanitise on output as well as on input when content can reach the database without going through the cast. <x-kodex::content> does this unless you pass clean.
  • Do not print content with {!! !!} unless it came out of the sanitiser.
  • allowed_classes is a list of things content authors can do to your page. Do not put utility classes in it that position, hide or cover elements.
  • allow_data_images lets content carry files that never went through the upload checks. Leave it off unless you need it.
  • Uploaded files are served by your web server from the upload disk. Serve that location as static files only (no script execution), and send X-Content-Type-Options: nosniff.
  • Links in content can point anywhere; the sanitiser makes them safe to click, not trustworthy.
  • The upload policy is tied to APP_KEY. Rotating the key invalidates policies already handed out.

Licence

MIT: see LICENSE. The built editor in dist/ includes open-source libraries (Tiptap, ProseMirror and others); their licences are reproduced in dist/THIRD-PARTY-NOTICES.txt.