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:
- session cookies are
HttpOnlyandSameSite=Laxby default and strict session ids are on - Larafony already configured sessions this way, so nothing changes for applications usingSessionManager; - a custom
SessionHandlerInterfaceimplementation withoutcreate_sid()andvalidateId()raises a warning (both become mandatory in PHP 9.0) - Larafony's file and database handlers implement them.
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)
-
Time\Durationis accepted wherever a number of seconds or aDateIntervalwas:Cache::put()/remember()/putMultiple()(also tagged caches and the PSR-16 adapter),CacheItem::expiresAfter(),Dispatcher::dispatchAfter(),HttpClientConfig::withTimeout()(rounded up to whole seconds),Instant::add()/sub(),FrozenClock::travel(),SystemClock::sleep()(nanosecond precision) and theuntilof Inertia once-props.Larafony\Framework\Clock\DurationConverterconverts aDurationfor APIs that count seconds or need aDateInterval. -
WebSocket engine (
FiberEngine) waits for sockets withIo\Poll(epoll / kqueue) instead ofselect(): the 1024-descriptor limit is gone and a handler may close its own connection.ext-socketsis still required. -
Stream failures are exceptions, not warnings:
StreamFactory::createStreamFromFile()throwsRuntimeExceptionfor a file that cannot be opened (as PSR-17 requires),File::ensureFileExists()says why the file cannot be read, andSmtpConnection::write()throwsTransportErrorwhen the server dropped the connection or took only part of a command - before, such a write failed silently.Larafony\Framework\Storage\StreamContextbuilds the contexts. -
URLs are assembled with
Uri\Rfc3986\UriBuilder, which fixed three defects:UrlGenerator::route()percent-encodes parameter values as one path segment (a b/cbecomesa%20b%2Fc). If you passed values that were already encoded, pass them raw now - they would be encoded twice. A base URL with a path or a trailing slash no longer yields//.UriFactory::createUriFromGlobals()appended the query string twice (/users?page=2?page=2).- SMTP credentials are percent-decoded when read from a DSN, so a password with
@,:or/passed toMailerFactory::createSmtpMailer()reaches the server unchanged. In a hand-written DSN write a literal%as%25. UriInterface::getAuthority()omits a missing user or port instead of returning@host:.
-
SMTP encryption works. The scheme of the mail DSN was parsed but never applied: every connection, credentials included, went out in plain text. Now
smtps://is TLS from the first byte andsmtp+tls://(smtp+starttls://) upgrades withSTARTTLSbeforeAUTH. The server certificate is verified against the DSN host, and a server that refusesSTARTTLSor presents an untrusted certificate aborts the delivery - there is no fallback to plain text. For a certificate signed by a private CA pass PHPsslcontext options:SmtpConfig::fromDsn($dsn, ['cafile' => '/path/ca.pem']). A server greeting other than2xxis now an error too.
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
- Inertia visits no longer trigger full page reloads.
ResponseFactoryanswered every InertiaGETwhoseAcceptheader containedtext/htmlwith409 X-Inertia-Location. The Inertia client (v1 and v3) always sendsAccept: text/html, application/xhtml+xml, so every navigation was a hard reload. The check is gone; external redirects are an explicitInertia::location()call now. - Asset versioning works.
InertiaMiddlewarecomparesX-Inertia-Versionon InertiaGETrequests withInertia::getVersion(); on mismatch it responds409withX-Inertia-Location(the full request URL) andX-Inertia-Version. Set the version per deploy, e.g.$inertia->version($manifestHash). Non-GETrequests are not checked. - Shared props reach the page.
Inertiawas never registered in the container, so the middleware andController::inertia()each got their own autowired instance and everything shared inInertiaMiddleware::getSharedData()was lost.ViewServiceProvidernow registers one instance per request (it needsServerRequestInterface, so keepHttpServiceProviderbeforeViewServiceProvider). urlkeeps the query string (/notes?page=2, previously/notes).props.errorsis always present and always a JSON object ({}by default); errors passed by the controller or shared win, anderrorssurvives partial reloads.- Partial reloads honour
X-Inertia-Partial-Exceptand only apply whenX-Inertia-Partial-Componentmatches the rendered component. Excluded lazy (callable) props are not evaluated. - Redirects to a URL with a
#fragmentafter an Inertia request become409+X-Inertia-Redirect(except prefetch requests,Purpose: prefetch). Vary: X-Inertiais added to every response passing throughInertiaMiddleware(existingVaryvalues are kept).
New API
Inertia::location(string $url)โ409+X-Inertia-Locationfor Inertia requests,302otherwise.Inertia::getVersion()is public.InertiaMiddleware::onVersionChange()โ protected hook, override to customise the version mismatch response.
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
- PSR-17 / PSR-18 discovery. The SDK's HTTP middleware (DNS rebinding, CORS, protocol version, OAuth) build
their factories through
php-http/discovery, ignoring the factories passed to the transport. Discovery only knows popular packages, so after the bump every/mcprequest failed withNo PSR-17 response factory found.HttpServiceProvidernow registersLarafony\Framework\Http\Discovery\LarafonyDiscoveryStrategy, which makes Larafony's PSR-17 factories andCurlHttpClient(PSR-18) discoverable โ for the MCP SDK and any other library usingphp-http/discovery. symfony/finderis a direct dependency. The SDK made it optional in 0.5, but MCP discovery (mcp.discovery.path) needs it. Without it a--no-devinstall does not fail โ discovery errors are logged and the server silently advertises no tools.php-http/discoveryis a direct dependency (used byLarafonyDiscoveryStrategy).McpControllerbuilds the SDK's default middleware stack (CorsMiddleware,DnsRebindingProtectionMiddleware) frommcp.http.allowed_origins/mcp.http.allowed_hosts.mcp:startwrites its startup messages to stderr: in the stdio transport stdout may only carry MCP messages.
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:
- the default is
['src'], andmcp:starthonoursmcp.discovery.dirstoo (it ignored the setting); - directories named
vendor,node_modules,storageortestsare skipped wherever they occur - change the list withmcp.discovery.exclude; - discovery results are cached when the application has a cache, but not in debug mode (
app.debug): the SDK never invalidates them, so a new tool would stay invisible. Force either behaviour withmcp.discovery.cache, and clear the cache when deploying new tools.
Applications with MCP classes outside src have to list those directories in mcp.discovery.dirs.
SDK changes worth knowing (0.2 โ 0.8)
- Tool/resource/prompt elements are loaded lazily on the first request (0.7) โ loader errors surface there, not at build.
- Protocol version negotiated during
initialize; one endpoint serves handshake-era and 2026-07-28 clients (0.8). - Not-found tools/prompts answer
-32602instead of-32002(0.8); list-shaped tool results go tostructuredContentonly on 2026-07-28 (0.8). - Roots, sampling and logging are deprecated by the spec (0.8, removal not before 2027-07-28).
- Positional arguments of
Builder::addTool()/addResource()/addPrompt(),Tool,McpTool,McpResource,McpPromptchanged (a$titlewas inserted, 0.5/0.6) โ use named arguments. Mcp\Schema\Resourcerenamed toMcp\Schema\ResourceDefinition(0.6).
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()):
- Interactive (stdin and stdout are terminals) โ the debugger as before.
- Non-interactive when stdin or stdout is not a terminal,
--no-interactionis passed to any command, orLARAFONY_NO_INTERACTION=1(true,yes) is set โ a one-shot plain-text report on stderr (no ANSI colors, no prompts): exception class and message,file:line, source excerpt, stack trace and the chain of previous exceptions.
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:
- An uncaught exception now always ends the process with exit code 1 (it was
0, so scripts and CI treated crashed commands as successful). The interactive debugger exits with1too afterexit. - If rendering the error itself fails, the handler prints the original exception class and message to stderr instead
of crashing inside the error handler (it passed a string to the
intexit callback โTypeError). ConsoleHandler::__construct(ConsoleRenderer $renderer, Closure $exit, ConsoleReportRenderer $reportRenderer = new ConsoleReportRenderer(), ?bool $interactive = null, ?Closure $errorOutput = null)โ the second argument is the process exit callback and receives the exit code;$interactive = nullauto-detects.E_USER_DEPRECATEDis no longer treated as a fatal error at shutdown. A silenced deprecation (error_reportingwithoutE_USER_DEPRECATED) left inerror_get_last()made a successfully finished command report aFatalError(and, before the non-interactive mode, start the endless debugger).
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:
- any other hash was hashed again โ including on every load from the database, since hydration goes through the same setter. Users with bcrypt hashes (migrated from Laravel, Symfony, Node, โฆ) could never log in;
- a plain password starting with
$argon2was stored as plain text.
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:
castBackruns when a property changes.Model::markPropertyAsChanged()storesAttributeCaster::castBack()of the value, so#[CastUsing(Instant::from(...), Instant::toDatetimeString(...))]writes2026-09-27 14:30:00(it wroteInstant::__toString(), ATOM:2026-09-27T14:30:00+00:00).- Attributes extending
CastUsingwork.AttributeCasterlooked the attribute up withoutReflectionAttribute::IS_INSTANCEOF, so#[ArrayCaster]was ignored even when reading. - Backed enums are stored as their value. Without a
castBackan enum wasjson_encode()d:Status::Activewas stored as"active"(with quotes) andStatus::from()could not read it back. ArrayCaster::toArray()tries JSON first. It split any value containing a comma, so JSON objects with more than one key ({"user_id":5,"ip":"โฆ"}) became garbage; plaina,b,clists still work.fill()accepts already cast values.fill()/forceFill()serve application code and database rows; an array or object that already has the property's type (array,Clock,Instant, enum, โฆ) is no longer passed to the cast callback (#[ArrayCaster]would get an array,Status::from()an enum).DatabaseLoguses#[ArrayCaster]forcontextandmetadata. Its$castsarray was never read, so a log row loaded from the database put a JSON string into anarrayproperty (TypeError).- Resolved
#[CastUsing]attributes are cached per class and property. - New
ClockFactory::toDatetimeString(Clock)โ the write counterpart ofClockFactory::parse(). Framework entities (User,Job) declare both directions:#[CastUsing(ClockFactory::parse(...), ClockFactory::toDatetimeString(...))]. Recommended for application models too; backed enums need nocastBack(stored as->value).
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.
-
Identifiers must be plain names. Columns, tables,
insert()/update()keys and join conditions acceptname,table.name,schema.table.nameand backtick-quoted segments (`order`); tables may carry an alias (users u,users as u). Anything else throwsInvalidArgumentException("Invalid SQL column name: ...") when the query is compiled. The generated SQL of valid queries is unchanged. -
Operators are whitelisted:
=,!=,<>,<,>,<=,>=,<=>,LIKE,REGEXP,RLIKEand theirNOTforms (case-insensitive).JOIN ... ONaccepts the comparisons only. -
select()accepts columns and simple function calls:*,users.*,name as n,COUNT(*) as total,COUNT(DISTINCT orders.id),COALESCE(a, b, 0). For anything else use the newselectRaw()- it puts the expressions into the query verbatim, so never build them from request input:DB::table('users')->selectRaw(["CONCAT(first_name, ' ', last_name) as full_name"])->get(); -
ORDER BYquotes qualified names correctly:orderBy('users.created_at')compiled toORDER BY `users.created_at`(one non-existent column) and now givesORDER BY `users`.`created_at`. -
Native prepared statements, one statement per query. The MySQL connection sets
PDO::ATTR_EMULATE_PREPARES => falseandPdo\Mysql::ATTR_MULTI_STATEMENTS => false.Schema::table()may still return several statements (add / modify / drop);Schema::execute()runs them one at a time. BC break: a hand-written SQL string with several;-separated statements is rejected - execute each statement separately. -
DatabaseInfo::getTable()validates the table name it puts intoDESCRIBE.
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.
-
fill()is for untrusted data. It sets only public properties declared by the entity. It skips - silently, like unknown keys - the primary key, the model's own properties (table,primary_key_name,use_uuid, ...), non-public properties and properties marked with the new#[Guarded]attribute:#[Guarded] public bool $is_admin { get => $this->is_admin; set { $this->is_admin = $value; $this->markPropertyAsChanged('is_admin'); } } -
forceFill()is for trusted data (database rows, seeders, application code): it also sets the primary key and guarded properties, never the model internals. Hydration (ModelQueryBuilder, relations) uses it. -
Userguards its account state:is_active,remember_token,password_reset_token,password_reset_expires,email_verified_at,last_login_at. BC break: code that passed these (orid) tofill()must assign them directly ($user->is_active = 1) or callforceFill().
Sessions and authentication
- The session is actually started.
SessionManager::start()configured the cookie and the handler but never calledsession_start(): unlesssession.auto_startwas on, nothing written to the session survived the request andAuth::login()failed onsession_regenerate_id(). It now starts the session (in the console there is no client, so commands get an in-memory session instead). - Strict session ids. The session starts with
use_strict_mode, and both handlers implementSessionUpdateTimestampHandlerInterface: an id the application did not issue (session fixation) is replaced with a fresh one.FileSessionHandleronly accepts ids made ofA-Z a-z 0-9 , -, so an id can never point outside the session directory. - Deactivated and deleted users are logged out.
UserManager::user()checkedis_activeonly inattempt(); it now checks it on every request, for the session and for the remember-me cookie. logout()always revokes the remember-me token (it was skipped when the user had not been resolved earlier in the request) and regenerates the session id.login()usesSessionManager::regenerateId(), which is a no-op without an active session.- Remember-me tokens are stored hashed (SHA-256); the cookie keeps the raw token. BC break: tokens stored
by 2.x no longer match, so "remember me" users have to log in once more. The
remember_tokencolumn (100 chars) is large enough.
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.
RouteServiceProviderregistersCachedAttributeRouteLoader. The cache now holds only the names of the classes that declare routes, per scanned directory, instorage/cache/routes.php. Routes are still built from the attributes, so nothing has to be serializable.- Off in debug mode (
app.debug);routing.cacheforces it on or off. - New
route:clearcommand - run it on every deploy. The cache is not compared against the files, so a controller added later is not routed until it is cleared. A cached class that no longer exists triggers a new scan. - BC break:
RouteCache::get()/put()work with class names instead ofRouteobjects;CacheLoader,CacheReaderandCacheWriterare gone. The oldstorage/cache/routes.cachefile is unused and can be deleted.
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.
- Models coming from the database (
get(),first(), relations) remember the loaded values;save()updates only the columns whose value differs. Values are compared as stored (1and'1'are the same). save()on an unchanged model runs no query.- After
save()the model is in sync again: a secondsave()writes only what changed in between. - The primary key is never part of the
SETclause. - New:
Model::syncOriginal()marks the current values as the database state - for code that hydrates models by hand (new Post()->forceFill($row)->syncOriginal()). Without it a hand-built model with an id still writes everything it holds, as before.
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
EncryptionService::decrypt()no longer instantiates objects. Decrypted data is unserialized withallowed_classes => false: scalars and arrays come back unchanged, objects as__PHP_Incomplete_Class. Pass the classes you expect (decrypt($value, allowedClasses: [Cart::class])) - or better, store arrays.- Encryption context.
encrypt($value, $context)/decrypt($value, $context)authenticate the context with the value, so a ciphertext only decrypts where it was meant to be used. - Cookies are bound to their name.
CookieManageruses the cookie name as the context: the value of one cookie cannot be replayed under another name. BC break: cookies written by 2.x no longer decrypt and are treated as absent (users log in again once). - Foreign cookies no longer break the request.
CookieManager::get()threw on any cookie the application had not encrypted itself (analytics, another app on the domain); it now returns the default, andall()skips them.
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.
Addressvalidates its input. An e-mail with whitespace, control characters or</>, and a name with control characters, throwInvalidArgumentException- validate form input before building anAddress. Quotes and backslashes in the name are escaped.SmtpCommandrefuses control characters in any command.- Control characters in the subject are replaced with a space.
- The message body is dot-stuffed (RFC 5321 ยง4.5.2) and its line endings normalized to CRLF: a line containing
only
.no longer ends the message.
Still open: mail.encryption is not applied by the SMTP transport yet (the connection is plain text).