Upgrading to Larafony 3.0

PHP 8.6 is required

Larafony 3.0 needs PHP 8.6 (2.x ran on 8.5): the framework uses partial function application (array_any($roles, $this->hasRole(?))). On PHP 8.6 itself:

OrderDirection is replaced by PHP's SortDirection (BC break)

Larafony\Framework\Database\Base\Query\Enums\OrderDirection is removed; orderBy() takes the enum built into PHP 8.6:

// before
use Larafony\Framework\Database\Base\Query\Enums\OrderDirection;

$query->orderBy('created_at', OrderDirection::DESC);

// after - SortDirection lives in the global namespace
$query->orderBy('created_at', \SortDirection::Descending);

OrderDirection::ASC becomes SortDirection::Ascending, OrderDirection::DESC becomes SortDirection::Descending. latest() and oldest() are unchanged.

New on PHP 8.6 (no changes required)

Inertia.js v3

Larafony ships its own server-side Inertia adapter (Larafony\Framework\View\Inertia), so there is no Composer package to bump โ€” 3.0 brings the adapter in line with the Inertia v3 protocol, which the @inertiajs/* 3.x clients expect.

What changed in the Inertia v3 protocol

Area Inertia v1 (what Larafony 2.x implemented) Inertia v3
Initial page object <div id="app" data-page="{โ€ฆ}"> (HTML attribute, entity-encoded) <script data-page="app" type="application/json">{โ€ฆ}</script><div id="app"></div> โ€” the v3 client reads only the script tag
JSON in the initial page HTML-entity encoded Plain JSON, / escaped as \/ so </script> cannot close the tag; no HTML entities
clearHistory / encryptHistory always present (false) only present when true
Lazy props lazy() lazy() removed (deprecated in v2) โ€” optional()
Partial reloads X-Inertia-Partial-Data plus X-Inertia-Partial-Except (only narrows first, except removes from that subset)
Prop types shared, lazy always, optional, deferred, merge/prepend/deep-merge (v2), once, scroll (v2.x), nested dot-notation paths (v3) โ€” announced through page object metadata (deferredProps, mergeProps, onceProps, sharedProps, โ€ฆ)
Redirects with #fragment fragment lost 409 + X-Inertia-Redirect (fresh Inertia visit keeping the fragment)
Client axios, qs, lodash-es, CommonJS own XHR client, ESM only, Vue 3 / React 19 / Svelte 5; events invalid โ†’ httpException, exception โ†’ networkError; router.cancel() โ†’ router.cancelAll()

Unchanged: X-Inertia / X-Inertia-Version request headers, JSON page object (component, props, url, version), 409 + X-Inertia-Location for asset version mismatches and external redirects, 302 โ†’ 303 after PUT/PATCH/DELETE.

Changes in Larafony

New @inertia Blade directive

Render the root element in your Inertia root view (default: inertia.blade.php) with the directive instead of building it by hand:

<body>
    @inertia            {{-- or @inertia('custom-id') --}}
</body>

It outputs the v3 script tag + mount point for the $page view variable (Larafony\Framework\View\Inertia\RootElement::render()).

Required app change โ€” replace the hand-written v1 element:

-<div id="app" data-page='<?php echo json_encode($page, JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT); ?>'></div>
+@inertia

Protocol fixes

New API

Inertia v3 prop types

Larafony\Framework\View\Inertia\Inertia exposes the v3 prop types as static factories. Props are resolved by PropsResolver, which also emits the page object metadata the client needs (deferredProps, mergeProps, prependProps, deepMergeProps, matchPropsOn, onceProps, sharedProps โ€” each only when non-empty).

use Larafony\Framework\View\Inertia\Inertia;

return $this->inertia('Dashboard', [
    // always included, even on partial reloads that did not ask for it
    'auth' => Inertia::always(fn () => $this->currentUser()),

    // never sent on a full visit, only when requested: router.reload({ only: ['users'] })
    'users' => Inertia::optional(fn () => User::all()),

    // left out of the first response, fetched by the client right after render; same group = one request
    'stats' => Inertia::defer(fn () => $this->stats()),
    'audit' => Inertia::defer(fn () => $this->audit(), 'slow'),

    // merged into the client's data on partial reloads (infinite lists, chat, ...)
    'posts' => Inertia::merge($page->items)->matchOn('id'),
    'messages' => Inertia::merge($messages)->prepend(),
    'feed' => Inertia::merge($feed)->append('data', 'id'),  // merge at a nested path, match on id
    'settings' => Inertia::deepMerge($settings),

    // resolved once, remembered by the client across visits
    'plans' => Inertia::once(fn () => Plan::all())->as('plans')->until(3600),

    // dot-notation keys and nested prop types are supported
    'user.permissions' => $permissions,
]);
Factory Full visit Partial reload Metadata
always($value) included always included โ€“
optional(Closure) skipped, not announced only when requested โ€“
defer(Closure, $group = 'default') skipped only when requested deferredProps[group][]
merge($value) / ->prepend() / ->append($path, $matchOn) / ->matchOn($key) included only when requested mergeProps, prependProps, matchPropsOn
deepMerge($value) included only when requested deepMergeProps
once(Closure) / ->as($key) / ->until($ttl) / ->fresh() included unless the client already has it (X-Inertia-Except-Once-Props) same onceProps[key] = {prop, expiresAt}

defer() and optional() can be combined with ->once(), defer() with ->merge(). Merge metadata is skipped for props listed in X-Inertia-Reset.

History encryption: $inertia->encryptHistory() and $inertia->clearHistory() add encryptHistory: true / clearHistory: true to the page object (omitted otherwise, as v3 expects).

Behaviour change: only closures and prop types are called

Previously every prop passing is_callable() was invoked, so a plain string that happens to name a PHP function was executed: 'clock' => 'time' was sent as a timestamp and 'sort' => 'max' threw ArgumentCountError. Array callables were no better: props often carry request input ('filters' => $request->query), and ?filters[x][]=Class&filters[x][]=method made the adapter call any public static method and send the result back.

Only Closures and the prop types (Inertia::always(), defer(), merge(), optional(), once()) are resolved now, at every nesting level. Strings, array callables and other invokable objects are sent as data - wrap them in a closure (fn () => Report::totals(), $service->stats(...)) if they are meant to be evaluated lazily.

Not implemented (yet)

Infinite scroll props (scrollProps, needs pagination metadata), rescued deferred props (rescuedProps), session flash data (flash) and preserveFragment, error bags (X-Inertia-Error-Bag), Precognition and SSR. The client handles their absence gracefully.

MCP SDK 0.1 โ†’ 0.10

mcp/sdk is bumped from ^0.1.0 to ^0.10.0 (latest release โ€” there is no 1.0 yet; 0.8.x has a security advisory). The SDK now speaks MCP spec revisions up to 2026-07-28 (stateless HTTP) next to the handshake-era ones (2025-06-18, 2025-11-25) from one /mcp endpoint. Larafony's tools, resources and prompts need no changes: the attribute API used by #[McpTool], #[McpResource], #[McpPrompt] and #[Schema] (named arguments) is compatible - only the imports move: SDK 0.10 renamed Mcp\Capability\* to Mcp\Server\Capability\* (e.g. Mcp\Server\Capability\Attribute\McpTool) and Mcp\Server to Mcp\Server\Server.

Required app changes

Allowed hosts for the HTTP endpoint (BC break)

Since SDK 0.6 the HTTP transport rejects requests whose Host / Origin is not on an allow-list (DNS rebinding protection). The default list is localhost, 127.0.0.1, [::1], so an /mcp endpoint served from a real domain answers 403 Forbidden until the domain is allowed:

// config/mcp.php
'http' => [
    // hosts the /mcp endpoint is served from (Host header)
    'allowed_hosts' => ['localhost', '127.0.0.1', '[::1]', 'mcp.example.com'],
    // browser origins allowed to call the endpoint, with scheme and port (default: none; same-origin always passes)
    'allowed_origins' => ['https://app.example.com'],
],

Access token for the HTTP endpoint (BC break)

The allow-lists above only stop browsers: any other client sends whatever Host / Origin it likes, and /mcp had no authentication at all - whoever could reach it could call every registered tool. McpController now requires Authorization: Bearer <token> and refuses every request (401) until a token is configured:

// config/mcp.php
'http' => [
    // one token or a list of tokens; generate with e.g. `php -r "echo bin2hex(random_bytes(32));"`
    'token' => EnvReader::read('MCP_TOKEN'),
    // only for an endpoint that is not reachable by anyone else (local development)
    // 'allow_unauthenticated' => true,
],

MCP clients send the token as a request header ("headers": {"Authorization": "Bearer ..."} in the client's server configuration). CORS preflight (OPTIONS) requests pass without it. The stdio transport (mcp:start) is unaffected.

Changes in Larafony

A session opened over HTTP belongs to the token that opened it (SDK 0.10 binds sessions to a principal): a request carrying the session id with another configured token is answered 404.

Discovery scans src only (BC break)

mcp.discovery.dirs defaulted to ['src', '.'], so every request reading the tool list walked the whole project, vendor/ included (about 1.4 s instead of 0.1 s for the framework repository). Now:

Applications with MCP classes outside src have to list those directories in mcp.discovery.dirs.

SDK changes worth knowing (0.2 โ€“ 0.8)

Console error handler: non-interactive mode

The console error handler used to always start the interactive debugger (Debug mode: (type 'help' ...)). Without a terminal โ€” CI, cron, pipes, AI coding agents โ€” stdin is at EOF, every prompt read an empty line, and the debugger printed Unknown command in an endless loop (about 100 MB of output in 10 seconds) and never exited.

The handler now picks a mode (Larafony\Framework\Console\Interaction::isInteractive()):

InvalidArgumentException: Row without email
  at /app/src/Console/Commands/ImportUsers.php:42

    40|         foreach ($rows as $row) {
    41|             if (! isset($row['email'])) {
>   42|                 throw new InvalidArgumentException('Row without email', previous: $e);
    43|             }

Stack trace:
#0 /app/src/Console/Commands/ImportUsers.php:28 App\Console\Commands\ImportUsers->import()
#1 {main}

Caused by: LogicException: CSV header missing
  ...

Behaviour changes:

User password hashing

User::$password hashes a plain password on assignment and keeps values that already are a hash. The "is it a hash" check used to be str_starts_with($value, '$argon2'), which broke in two ways:

The check is now the one Laravel uses (Hash::isHashed() โ†’ password_get_info($value)['algo'] !== null), recognising every algorithm PHP supports (argon2i, argon2id, bcrypt $2y$), plus the legacy bcrypt variants $2a$, $2b$, $2x$: password_get_info() only knows PHP's own $2y$, while password_verify() accepts all of them. Those are matched by a strict pattern (cost 04โ€“31, 53 characters of salt and hash) so look-alike strings are still hashed. New passwords are hashed with Argon2id, as before.

Rehash on login

Like Laravel's rehash_on_login, UserManager::attempt() upgrades outdated hashes: after the password was verified and the user is active, User::rehashPasswordIfRequired($password) re-hashes and saves it when password_needs_rehash() reports a different algorithm or options than User::PASSWORD_ALGORITHM (Argon2id). Users migrated with bcrypt ($2y$, legacy $2a$โ€ฆ) or argon2i hashes move to Argon2id on their next login; wrong passwords and inactive users never trigger a write. The new hash is made with password_hash() directly, so a plain password that happens to look like a hash is still hashed.

New API: User::PASSWORD_ALGORITHM, User::passwordNeedsRehash(), User::rehashPasswordIfRequired(string $plainPassword).

ORM attribute casting: castBack on write

#[CastUsing(callback, castBack)] documented a write-side cast, but AttributeCaster::castBack() was never called: values were converted for the database by PropertyObserver::toString() alone. Fixed together with the issues it hid:

Query builder: identifiers and operators are validated

Values were always bound, but table names, column names and operators were concatenated into the SQL as given - and the connection emulated prepares, which also allowed stacked queries. ->orderBy($request->query['sort']) or ->where($column, $operator, $value) with request input was an SQL injection.

ORM: mass assignment protection

Model::fill() set every property that exists on the object, so new User()->fill($request->body) let the request choose the row to overwrite (id), the table (table), the key (primary_key_name) and flags like is_active.

Sessions and authentication

Error pages: fatal errors respect debug mode

DetailedErrorHandler rendered the debug page (message, paths, stack trace, source code) for fatal errors (E_ERROR, out of memory, ...) even with debug off. Fatal errors now take the same path as exceptions: the debug page only in debug mode, errors.500 otherwise - and plain Internal Server Error if that view cannot be rendered during shutdown.

Routing: attribute routes are scanned once

Router::loadAttributeRoutes() walked the controller directory on every request: read each file, extracted the class name, loaded and reflected the class. RouteCache / CachedAttributeRouteLoader existed but were never used - and could not be: they serialized Route objects, which drag the container along.

This removes the directory scan (about a third of the cost for 150 routes); building the route objects from the attributes still happens on each request.

ORM: save() writes only changed columns

A loaded model marked every column as changed, and nothing ever reset that: save() always sent an UPDATE with all columns (the primary key included), so two requests editing different fields of one row overwrote each other.

Blade: view data cannot replace the included template

BladeAdapter extracted the view data into the scope that held the path of the compiled template, so a data key named cached_file (for example from $this->render('search', $request->getQueryParams())) made it include any PHP file. Templates are now evaluated in their own scope, whose variables the data cannot overwrite; $this keeps working, a this key in the data is ignored. An exception thrown by a template no longer leaves an output buffer open.

Encryption and cookies

Mail: SMTP injection

Addresses, the subject and the body went into the SMTP conversation as given, so a line break in any of them (a contact form's "your e-mail" or "subject" field) could add recipients, headers or whole SMTP commands.

Still open: mail.encryption is not applied by the SMTP transport yet (the connection is plain text).