Skip to content

PHPantom — Laravel

Known gaps and missing features in PHPantom's Laravel Eloquent support. For the general architecture and virtual member provider design, see ARCHITECTURE.md.

Items are ordered by impact (descending), then complexity (ascending) within the same impact tier.

Label Scale
Impact Critical, High, Medium-High, Medium, Low-Medium, Low
Complexity Low (mechanical/boilerplate, no design decisions), Medium (self-contained, follows an existing pattern), Medium-High (spans modules, some new design), High (shared/core subsystem, correctness or performance tradeoffs), Very High (cross-cutting architecture, wide blast radius)

Out of scope (and why)

Item Reason
Container bindings registered dynamically or conditionally Binding names or targets computed at runtime (variables, environment switches, loops) cannot be recovered statically. Literal bind('name', Target::class)-style registrations in app and package service providers are recovered, as are the $bindings / $singletons arrays. Names in the framework's own registerCoreContainerAliases() and the app's alias config already resolve via parsing.
Facade getFacadeAccessor() with string aliases Requires booting the application. @method static tags provide a workable fallback.
Blade templates Separate project. See blade.md for the implementation plan.
Model column types from a live database connection Requires a reachable, migrated database plus credentials, and answers "true for that database" rather than "true for this code". Committed schema artifacts (migration files, database/schema/*.sql dumps) are now parsed statically (schema dump + migration scanning).
Legacy Laravel versions We target the generic annotation style current Laravel and the PHPStan Laravel extensions use. Older code may degrade gracefully.
Application provider scanning Low-value, high-complexity.
Macro discovery (Macroable trait) Requires booting the application to inspect runtime $macros static property. @method tags provide a workable fallback.
Facade → concrete resolution via booting Requires booting (getFacadeRoot()). When getFacadeAccessor() returns a ::class reference, static resolution is possible without booting. See "Facade completion" section below.
Contract → concrete resolution Fully out of scope, including core framework contracts. Calling a concrete-only method on a contract-typed value is unsound per the declared types — the diagnostic is intended, exactly as fn (A $a) => $a->bMethod() is not a false positive just because B extends A at every call site. Where the framework's own docblock is needlessly wide, fix the docblock upstream or via stub patches.
Manager → driver resolution Requires instantiating the manager at runtime.
Narrowing a MorphTo relation to concrete models $comment->commentable resolves to the generic Illuminate\Database\Eloquent\Model, which is what the relation declares. The morph map is global rather than per-relation, so the only type it could supply is a union of every mapped model — a sound upper bound that is far wider than the truth and would report a concrete method as "not found on any of the N possible types". Annotate the relation with @return MorphTo<Post\|Video, $this> where the target set is actually known.

Philosophy (unchanged)

  • No application booting. We never boot a Laravel application to resolve types.
  • Declared types are the contract. A diagnostic is a false positive only if the code is correct per the declared types of what it calls. Code that works because of runtime container state (contract-typed values whose binding happens to be a specific concrete, string aliases from arbitrary providers) is flagged intentionally; the remedy is an assert, a narrower type in the code, or an upstream docblock fix — never a resolver assumption baked into PHPantom. When we do read framework/project facts, we parse the installed source and bail gracefully if the shape is unrecognized; we never ship version-specific baked-in lists.
  • Code-declared types win. Column types declared in code (casts, accessors, @property tags, attribute defaults) are the most accurate source and always take precedence. Committed schema artifacts (migration files, database/schema/*.sql dumps) are now parsed statically via schema dump and migration scanning. A live database connection remains out of scope.
  • Generic relationship hints preferred. We expect relationship methods to carry the generic @return HasMany<Post, $this> annotation that the PHPStan Laravel extensions read. Fallback heuristics are best-effort.
  • Facades rely on @method tags. Laravel's facades ship with comprehensive @method static tags (2,047 across all facades as of Laravel 12.x) generated by a script. Our PHPDoc provider already parses these, and where a tag is too wide because the generator flattened it, a static call falls through to the class the facade's getFacadeAccessor() names. The residual gap is upstream: the generator throws away template parameters, generic arguments and conditional returns that the source method declares. See L1.

L1. Facade completion — upstream @method generator improvement

Facades are the primary way Laravel developers interact with framework services (Cache::get(...), DB::table(...), Route::get(...), etc.). The facade pattern works by forwarding static calls on the facade class to instance methods on a concrete service class via __callStatic().

Every facade already ships with comprehensive @method static tags (2,047 tags across all facades in Laravel 12.x), generated by Laravel's facade-documenter script.

The problem: flattened signatures

The generator throws away everything the source method's docblock says beyond a bare type name. The Application class has:

/**
 * @template T of object
 * @param class-string<T> $abstract
 * @return T
 */
public function make($abstract) { ... }

But the App facade emits:

@method static object|mixed make(string $abstract, array $parameters = [])

Four separate losses, all in facade.php:

  • Template parameters (T of object) are resolved to their bound or to mixed.
  • Generic arguments are dropped (Collection<int, User> → Collection).
  • Conditional returns are unioned (($id is int ? static : Collection) → static|Collection).
  • class-string<T> collapses to string, losing the binding that connects the argument to the return.

Every consumer of the tags — us, PHPStan, Psalm, PhpStorm — is left with a signature far wider than the truth.

Why this has to be fixed upstream

Resolving facades ourselves by parsing getFacadeAccessor() covers only part of the problem:

  1. Half the facades use string aliases. Auth returns 'auth', Cache returns 'cache', DB returns 'db'. We resolve the ones the framework's own registerCoreContainerAliases() and the app's config declare; a binding registered at runtime by an arbitrary provider stays unresolvable without booting.
  2. The @see annotations are informal. Facades list multiple @see classes (e.g. Auth references both AuthManager and SessionGuard), and the relationship between them isn't formal (one may be a @mixin of the other). We'd be reverse-engineering an undocumented script's output logic.
  3. Only PHPantom would benefit. Any resolution technique we build is specific to our tool. Other IDEs and LSPs face the same problem.
  4. Manager pattern complicates things. Many facades delegate to a "manager" class (AuthManager, CacheManager) which in turn delegates to a "driver" (SessionGuard, FileStore). The @method tags are already a flattened merge of both levels. We'd need to replicate that merging logic.

Upstream generator changes

PR target: laravel/facade-documenter (https://github.com/laravel/facade-documenter). The entire generator is a single file (facade.php, ~850 lines) that uses PHPStan's own phpDoc parser. The functions that flatten:

  • resolveDocblockTypes() — the GenericTypeNode branch strips generic arguments entirely. Needs to preserve args in the output string.
  • handleUnknownIdentifierType() — when encountering a template parameter like T, resolves it to its bound (T of object → object) or mixed. Needs to instead emit T as-is and add a <T of object> clause after the method name in the @method tag.
  • ConditionalTypeForParameterNode handling — unions the if/else branches. Needs to preserve the conditional syntax verbatim.
  • The class-string case in IdentifierTypeNode handling — maps class-string to string. Needs to preserve class-string<T>.

Tooling support for the richer syntax

Laravel will not emit tags that break the tools their users run, so the four changes have very different odds. Support as researched:

Change PHPStan Psalm PhpStorm Intelephense PHPantom
Generic args (Collection<int, User>) yes yes yes, since 2022.1 (WI-62267, Verified) unknown yes
Conditional return (($id is int ? A : B)) yes yes unknown yes, since 1.15.0 yes
class-string<T> preserved yes yes needs the template below unknown yes
Inline <T of object> after the method name yes no no unknown yes

The last row is the blocker. PhpStorm reports a false-positive Undefined class 'T' inspection for a template referenced from a @method tag (WI-64921, Open since 2022; the inference half is WI-72659, In Progress). Psalm parses each @method entry with its own ParseTreeCreator and raises InvalidDocblock when the entry does not come out as a method tree; its method-name regex requires the name to be followed directly by (, so make<T of object>( is not recognised as a method at all (Internal/PhpVisitor/Reflector/ClassLikeDocblockParser.php). Neither degrades gracefully.

So split the upstream work:

  1. Generic arguments, conditional returns, class-string without a template arg. No known breakage anywhere, immediate benefit in four tools. Submit these first, as separate PRs so one contentious change cannot stall the rest.
  2. Inline templates. Hold until PhpStorm ships WI-64921/WI-72659, or propose it as a @phpstan-method line that coexists with the plain @method so tools that choke keep reading the flattened one.

Impact: High · Complexity: High (upstream PRs)


Model property source gaps

The LaravelModelProvider synthesizes virtual properties from several sources on Eloquent models. The table below summarises what we handle today and what is still missing.

What we cover

Source Type info Notes
$casts / casts() Rich (built-in map, framework As* class casts with of() / using() generics, custom cast get() return type, enum, Castable, CastsAttributes<TGet> generics fallback)
$attributes defaults Literal type inference (string, bool, int, float, null, array) Fallback when no $casts entry
$fillable, $guarded, $hidden, $visible mixed Last-resort column name fallback
Legacy accessors (getXAttribute()) Method's return type
Modern accessors (returns Attribute) First generic arg of Attribute<TGet>, or mixed when unparameterised
Relationship methods Generic params or body inference
Relationship *_count properties int {snake_name}_count for each relationship method

Gaps (ranked by impact ÷ effort)


L45. *_count properties are offered on every relationship

Impact: Low-Medium · Complexity: High

For each relationship method we synthesize a {snake_name}_count property typed int, unconditionally. At runtime the attribute only exists when the query that produced the model called withCount() / loadCount(), or when the model lists the relation in $withCount. So $post->comments_count completes and hovers cleanly even where it is guaranteed to be null, and a user reading the completion list cannot tell which of the two comments-derived entries is real.

The trade-off is deliberate: withCount() is common enough that dropping the properties entirely would cost more than it gains, and the alternative needs call-site tracking we do not have. Doing this properly means threading "which counts were eager-loaded" from the builder chain (Post::withCount('comments')->first()) into the model type, which is the same machinery L8 needs for withSum() and friends. $withCount on the model is the easy half and could be read declaratively like $casts is today.

Until then the properties stay, so this is a precision gap rather than a missing feature. Reported as a follow-up on #312.

L8. withSum() / withAvg() / withMin() / withMax() aggregate properties

Impact: Low-Medium · Complexity: High

Less common than withCount; only affects codebases using aggregate eager-loading. Cannot be inferred declaratively from the model alone; requires tracking call-site string arguments.

Similar to withCount, these aggregate methods produce virtual properties named {relation}_{function}_{column} (e.g. Order::withSum('items', 'price') → $order->items_sum_price). The same call-site tracking challenge applies, and the type depends on the aggregate function (withSum/withAvg → float, withMin/withMax → mixed).

The @property workaround applies here too.

L10. RedirectResponse::withX() dynamic methods

Impact: Low · Complexity: Medium

Most code uses ->with('key', $value) instead of the dynamic ->withKey($value) form. Explicitly declared methods (withErrors, withInput, etc.) already work, and view('home')->withUser($user) already resolves to View because View::__call is documented @return \Illuminate\View\View.

Illuminate\Http\RedirectResponse supports the same dynamic with*() calls via __call(), but its __call is documented @return mixed, so redirect('/')->withFoo($x) raises no diagnostic and loses the chain:

redirect('/')->withFoo($x)->withErrors($errors);   // withFoo() returns mixed

Larastan handles this in RedirectResponseMethodsClassReflectionExtension, which treats any with* call as valid and returning $this.

Where to change: a stub patch on RedirectResponse::__call that returns static when the method name starts with with, or a small virtual member provider for the one class.


Laravel string-context intelligence (completion, hover, diagnostics)

This is the set of features that live inside string literals passed to Laravel helpers and facades: route('...'), config('...'), env('...'), __('...'), view('...'), and so on. The official Laravel VS Code extension (https://github.com/laravel/vs-code-extension) is built almost entirely around this layer, and PhpStorm + Laravel Idea cover it too.

Why we do this statically (and they boot the app)

The PHPStan Laravel extensions gather these facts by booting the user's application in the background and introspecting the live container (app('router')->getRoutes(), config()->all(), app()->getBindings(), etc.). The Laravel LSP does the same through php artisan tinker --execute: 14 of its 18 data providers (routes, configs, translations, views, models, middleware, auth, bindings, Blade components, paths, …) run injected PHP inside the booted app; only env vars, public assets, the Mix manifest, and controller names (regex-scraped) are gathered statically. Its Eloquent column completion even shells out to artisan model:show --json per model, which requires a reachable, migrated database. PhpStorm's Laravel Idea and barryvdh/laravel-ide-helper do the same thing differently: they generate a snapshot (JSON payload or PHP stubs) that the IDE then reads.

All three share two problems:

  1. A snapshot is one environment on one code path. The booted values reflect whatever bindings, config, and routes are registered under the default boot. A controller that rebinds a service, a config value that differs in production, or a route registered behind a feature flag is either invisible or actively wrong. The answer is "true for that boot," not "true here."
  2. Staleness. A snapshot is only as fresh as its last regeneration (manual for ide-helper, periodic background re-boot for the extension). Static scanning with a file watcher updates the instant the source file changes, not at the next heartbeat.
  3. Silent total failure. When the app cannot boot (broken provider, missing .env, no database), the Laravel LSP's tinker call exits nonzero and every boot-dependent feature silently returns empty: completions, hovers, and diagnostics all vanish with no indication why. A static scanner keeps working on a project that doesn't boot — which is exactly when the developer needs tooling most.

Our position (consistent with the No application booting philosophy above): the overwhelming majority of these facts live in static files we can parse and keep fresh for free — routes/*.php (->name()), config/*.php return arrays, lang/** PHP + JSON, .env, and resources/views/**. We recover ~90% of the value with no code execution, no stale snapshot, and correct behaviour on a project that doesn't even boot. The dynamic tail (routes/config/bindings registered at runtime by a closure) is the only part a snapshot wins on, and that is exactly the code that is hard to reason about anyway.

What already works

Go-to-definition is implemented for route names (route()), config keys, env vars, translation keys, and view names via the declaration scanners in virtual_members/laravel/{route_names, config_keys, env_vars, trans_keys, view_names}.rs. These walk the relevant source files and resolve a string key to its declaration site. Asset paths (asset(), mix(), @vite) and Inertia pages resolve against the filesystem at request time (virtual_members/laravel/assets.rs). StringKey also flows through find-references (rename, highlight, and semantic tokens are L31). Eloquent relation and column name strings have completion (completion/eloquent_string.rs).

The scanners already enumerate every valid key for go-to-definition. The items below mostly wire that existing enumeration into three more LSP endpoints rather than building new analysis.

L71. Inertia page props and asset helpers on a typed URL generator

Impact: Low · Complexity: Low-Medium

Inertia page names complete, navigate, and are checked, but the props a render passes in its second argument (Inertia::render('Users/Show', ['user' => …])) are not completed from the page's defineProps (Vue) or its component's props type. Reading them means parsing the page's <script setup> block or TypeScript props, which the Laravel extension does with a regex and only for Vue.

Separately, asset() paths are recognised through the helper, the URL facade, and url()->asset(), but not on a receiver only its type says is a URL generator ($this->url->asset('css/app.css') on an injected UrlGenerator). That needs a typed receiver site like the one view names use (view_receiver_method).

L27. Legacy Controller@method action strings

Impact: Low · Complexity: Low

We already complete and resolve the modern [Controller::class, 'method'] array form (which the Laravel LSP does not complete), and method-name strings inside Route::controller() groups. The legacy 'App\Http\Controllers\FooController@method' string form gets nothing. Split on @, resolve the class through normal resolution (honoring any group namespace prefix), and provide completion, go-to-definition, and an unknown-action diagnostic. Low priority: the string form is discouraged since Laravel 8.

L60. Read relation callback overrides and fallbacks from the declared signature

Impact: Low · Complexity: Low-Medium

Relation-callback inference steps aside when the application redeclares a relation-query method, and falls back to a fixed type when it cannot resolve the relation. Both decisions ignore what the declaration says:

  • Restated @method tags. Any @method whereHas(...) or @method with(...) on a model or builder (declared_relation_method in type_engine/variable/forward_walk/relation_callbacks.rs) counts as an application override and turns inference off for that class, even when the tag only restates the framework signature (a common pattern in hand-maintained IDE docblocks). Treat a declaration as an override only when its callback parameter type differs from the framework's.
  • Hard-coded eager fallback. An eager-array callback whose relation path cannot be resolved gets Relation<mixed, mixed, mixed> built in code rather than the element type of the declared $relations parameter. It matches Laravel's current declaration but will drift if the stub changes; read the declared type instead, as the other relation callbacks do.

L29. Livewire and Volt component names

Impact: Low (Livewire projects only) · Complexity: Low-Medium

Class components under the Livewire class namespace (app/Livewire/, nested names), the <livewire:foo-bar> tag resolution on the Blade side, and hover on a Livewire component's public properties via $this in its view are implemented (blade/discovery.rs). Three gaps remain:

  • View-based components. Volt and Livewire v4 single-file components (a Blade view that carries its own component class) are not indexed, so <livewire:…> naming one resolves to nothing.
  • PHP-side triggers. Volt::route('/path', 'component') (arg 1) and Route::livewire() get no completion, go-to-definition, or unknown-component diagnostic.
  • wire: attribute values. wire:model="…" names a public property of the component and wire:click="…" one of its public methods (the actions backing_class.rs already tells apart from view variables). Neither value completes, navigates, or reports a name the component does not declare. Laravel Idea reports an unknown wire:click action.

L31. String-key rename, highlight, and semantic tokens

Impact: Low-Medium · Complexity: Medium

References and go-to-definition already work for indexed Laravel string kinds, but the rename, document-highlight, and semantic-token arms are explicit no-ops. Wiring them up exceeds the Laravel LSP (which has none of the three): renaming a translation key updates the lang files across every locale plus all usages; renaming a route name updates the ->name() declaration and all usages; highlight and semantic tokens reuse the existing spans. Renaming a view name implies moving the Blade file — defer that one until the rest is in place. Symfony service IDs and container parameters are string-key spans too, declarations included, so their rename comes with the same work.

L57. Laravel queue names

Impact: Low-Medium · Complexity: Medium

->onQueue() names are free-form rather than config-backed. Complete from literals seen elsewhere in the project and connect those occurrences for navigation and references, but do not diagnose a name merely because the static index has not seen it.

L39. Unused view and translation key detection

Impact: Low · Complexity: Medium

The reverse of the invalid-key diagnostics: keys that are declared but never referenced. The references machinery already finds all usages of a view name or translation key; inverting it over the declaration sets yields unused views (no view()/@include/@extends/mailable reference anywhere) and unused translation keys. Surface as an opt-in workspace report (CLI analyze flag and/or code lens on the declaration), not as always-on diagnostics — dynamic construction (view("emails.$type")) makes "unused" inherently a heuristic, so it must read as "no static reference found," never as an error.

L49. Unguarded Eloquent mass assignment diagnostic

Impact: Medium · Complexity: Medium

A model that declares neither $fillable nor $guarded is totally guarded: Model::create($request->all()) (and fill()/update()) throws MassAssignmentException for any attribute at all, a common first-app footgun with no signal today. (Silently dropping unknown keys only happens once $fillable is declared.) Flag a call whose attribute-array argument is not a literal (so its keys can't be checked individually) and whose target model declares neither $fillable nor $guarded, nor the #[Fillable]/#[Guarded]/#[Unguarded] model attributes, and the project never calls Model::unguard(), on create(), fill(), update(), updateOrCreate(), firstOrCreate(), and firstOrNew(). The model resolution and column-source machinery used by attribute-array key completion shares the same receiver-typing path as the diagnostic's model-argument matching, so reuse it.

Where to look: virtual_members/laravel/model_extraction/ for existing $fillable/$guarded reads; diagnostics/ for the call-site diagnostic pattern used by similarly-shaped checks.

L61. Resolve aliased facade imports during route discovery

Impact: Low-Medium · Complexity: Medium

Route discovery recognizes Route and its fully qualified facade name, but does not resolve renamed imports. For example, use Illuminate\Support\Facades\Route as Routes; followed by Routes::resource('photos', PhotoController::class) leaves photos.show out of completion and reports it as an unknown route. This also affects ordinary named routes and the plural and singleton registration forms. Resolve the receiver through the source file's namespace and imports, including grouped imports, without treating unrelated classes named Route as the framework facade.

Where to look: virtual_members/laravel/route_names/discovery.rs and virtual_members/laravel/route_names/traversal.rs, particularly GroupPrefix::chain_reaches_router() and is_facade().


Editor features Laravel Idea has that do not live inside a string.

L67. Laravel refactoring intentions

Impact: Low-Medium · Complexity: Medium

Laravel Idea's intention actions with no counterpart here, grouped because each is a small, independent code action:

  • Convert a pipe-delimited rule string to an array, and a rule to its Rule:: object form.
  • Extract an inline $request->validate([...]) into a new FormRequest and type-hint it on the action.
  • Replace a facade call with an injected dependency (constructor property), and back.
  • In Blade, toggle {{ }} and {!! !!}, and extract a selection into a new component.

Pick them off individually; none depends on another.


Test suites and benchmarks

L68. Port Larastan's type and rule tests

Impact: High · Complexity: Medium

The Symfony, Doctrine, and WordPress extensions' tests are ported in tests/phpstan_symfony/, tests/phpstan_doctrine/, and tests/wordpress_stubs/. Larastan's are not, though Laravel is the framework PHPantom is measured on most. Its tests/Type/data/ holds about ninety assertType() fixtures (Eloquent builders and relations, collections, config(), app()->make(), facades, abort(), request input, model properties), and tests/Rules/ nineteen rule tests.

Port them into tests/larastan/ the same way: the type fixtures run by tests/assert_type_runner.rs, the rule tests as .fixture files in tests/fixtures/larastan/, a slice of laravel/framework copied by scripts/extract-framework-stubs.php as the stubs, and upstream's tests/application/ (models, migrations, config) as the project they run in. Larastan boots that application; we read the same files statically.

Larastan's types are not the reference: where one disagrees with what the framework actually returns, assert the correct type and say why in the README. Rule tests for checks PHPantom has no counterpart for and does not plan one (Octane compatibility, env() outside config, unnecessary collection calls) are listed in the README as not ported, not marked SKIP. Every other gap is a // SKIP: reason filed in docs/todo/.

L69. Benchmarks for Laravel string names and Blade

Impact: Medium · Complexity: Low-Medium

benches/laravel_completion.rs measures Eloquent member and morph column completion only. Symfony and Yii benchmark their name completion over a generated application (benches/symfony_completion.rs, benches/yii_completion.rs); Laravel, with the most string contexts of any framework, has no equivalent. Add one that generates an application with a few hundred routes, config keys, views, and translation keys, and times completion inside route('…'), config('…'), view('…'), and __('…'), plus completion of a variable and a member inside a Blade template whose type comes from its signature. Register it in Cargo.toml so benches/ci_benchmarks.py picks it up.