Download the PHP package amrachraf6699/laravel-nplusone-scanner without Composer

On this page you can find all versions of the php package amrachraf6699/laravel-nplusone-scanner. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package laravel-nplusone-scanner

# Laravel N+1 Query Scanner

amrachraf6699/laravel-nplusone-scanner is an offline, AST-based static analyzer for potential Laravel N+1 query patterns. It scans PHP source code without executing the scanned application, sending HTTP requests, instantiating application models, connecting to a database, or waiting for lazy-loading exceptions.

The current release is v0.1.1. Findings are intentionally conservative: they identify code worth reviewing, not runtime proof that an N+1 query will occur.

Contents

Why this package exists

An N+1 query happens when an application loads a collection and then performs another database query for each item in that collection. For example, loading all users with one query and then lazily loading posts once per user can turn a page into dozens or thousands of queries.

The package catches common source-level shapes before they reach production or CI. It is useful during code review, local development, and automated checks where a database or HTTP environment is unavailable.

What it does and does not do

The scanner does:

The scanner does not:

The reusable scanner core is isolated from Laravel’s container. When run through Artisan, Laravel still boots the host application before the command is dispatched; providers in that host application may perform their own work. The package itself does not execute the files it scans.

Requirements and compatibility

This is a Composer library, so composer.lock is intentionally not committed. CI resolves dependencies independently for each PHP lane: PHP 8.2 selects the compatible Laravel 12/Testbench 10 set, while PHP 8.3 and newer select Laravel 13/Testbench 11 when available.

Installation

Install the package in a Laravel application:

Laravel package auto-discovery registers the service provider. Publish the optional configuration file:

The package does not require a database connection for scanning.

Quick start

Run the default scan:

Scan a specific directory and fail CI on high-severity findings:

Produce machine-readable output:

Scan more than one path by repeating the option:

Command options and exit codes

The command is nplusone:scan.

Option Meaning
--path=PATH Repeatable directory or PHP file to analyze. When supplied, it replaces configured analysis paths.
--format=console\|json Select human-readable console output or deterministic JSON. Defaults to console.
--min-severity=low\|medium\|high Report only findings at or above this severity.
--fail-on=low\|medium\|high Return exit code 1 when a reported finding reaches this threshold.
--no-progress Suppress progress text in console output. Always use this for redirected output.

Exit codes:

Code Meaning
0 The scan completed and no reported finding reached --fail-on. This also covers a completed scan with findings when no threshold was requested.
1 The scan completed and at least one reported finding reached --fail-on.
2 Invalid options or configuration, unreadable input, parser errors, or another analysis failure.

A scan with independent file errors is reported as partial and returns 2. An empty readable directory is a successful zero-file scan.

Detection rules

N1 — relationship property inside an iteration

N1 reports a recognized relationship property accessed on a varying model inside a verified iteration when that relationship is not known to be loaded.

Potential candidate:

Preferred version:

The preferred version is not reported when the User::with('posts')->get() provenance is recognized.

N1 does not treat ordinary PHP properties as relationships. The relationship must be established from model source metadata or a reliable indexed inheritance chain.

N2 — relationship query method inside an iteration

N2 reports explicit relationship-method queries inside a verified iteration. This matters because explicit method calls still query even when lazy-loading protection is enabled.

Potential candidate:

For count and existence checks, the suggestion matches the operation:

Supported relationship query terminals include count, exists, first, get, sum, avg, max, min, and pluck. Unsupported or dynamic query chains are treated as unknown.

N3 — proven collection callbacks

N3 reports the same kind of risk inside callbacks known to operate on a recognized Eloquent model collection.

Potential candidate:

Safe eager-loaded callback:

The scanner does not assume that every method named map() or each() belongs to an Eloquent collection. Callback parameters have their own scope, so shadowed variables do not inherit stale outer facts.

N4 — Laravel API Resource relationship access

N4 is a conservative Resource warning. It requires a Resource model established through an explicit configuration mapping or an unambiguous @mixin annotation.

Potential candidate:

Safe conditional relationship:

N4 does not prove that the caller omitted eager loading. It remains a lower-confidence review item.

Native loop support

Indexed access to a known model collection is supported conservatively in for, while, and do-while loops:

These findings receive medium confidence. A fixed model does not qualify merely because it appears in a loop:

Eager loading and aggregate awareness

Recognized relationship loading includes:

The scanner tracks relationship paths conservatively. Loading posts does not establish that posts.comments is loaded.

Aggregate attributes are separate from relationship loading:

withExists, loadCount, and loadExists are treated as aggregate operations. They do not make $user->posts safe.

Collection relationship autoloading is recognized as a loading-state caveat. The scanner does not execute application providers to discover whether automatic eager loading is enabled at runtime.

Severity and confidence

Severity estimates potential performance impact. Confidence estimates how strongly source evidence supports the finding.

Rule/context Typical severity Typical confidence
Recognized relationship property in a verified foreach High High
Explicit relationship query in a verified iteration High High
Indexed for, while, or do-while candidate High Medium
Proven Eloquent collection callback High High
Resource relationship access Medium Low

A high-confidence finding is still a static warning. It does not establish row counts, runtime branches, caller loading state, or actual SQL.

Configuration

The default configuration is:

Publish it with:

Configuration details:

Example Resource mapping:

Do not use dynamic relationship names when you need a high-confidence static result:

Console and JSON reports

Console output includes the scanner version, files analyzed, issue count, severity, file, line, model, relationship, and suggestion.

JSON output contains a deterministic object with this shape:

status can be complete, partial, or failed. Diagnostics describe parse, read, duplicate-declaration, and unresolved-Resource conditions.

For CI, keep progress and human-readable output out of stdout:

Model and relationship discovery

The scanner never executes model methods. It recognizes local models through canonical Eloquent roots and transitive local inheritance:

Supported relationship factories include hasOne, hasMany, belongsTo, belongsToMany, morphOne, morphMany, morphTo, morphToMany, morphedByMany, hasOneThrough, and hasManyThrough.

The resolver uses fully qualified names produced from namespaces and imports. It does not guess from arbitrary class suffixes. If a model or relationship cannot be identified reliably, the analyzer abstains.

False positives, false negatives, and limitations

A finding can be a false positive when runtime loading happens outside the source evidence available to the scanner. Common examples include:

The scanner deliberately downgrades confidence or abstains in these cases rather than inventing model or relationship identity.

A false negative can occur when a query is hidden behind a repository, custom scope, dynamic method, runtime relationship resolver, generated code, Blade template, or unsupported iterator. Zero findings never proves that an application is N+1-free.

The scanner also reports only potential repeated work. It cannot determine runtime collection size, SQL query count, indexes, network latency, or whether a relationship is already hydrated through another application mechanism.

CI usage

The repository workflow runs on PHP 8.2, 8.3, and 8.4. It resolves dependencies per lane because Laravel 12 and Laravel 13 have different PHP requirements, then runs:

A consuming application can fail its own CI on high-confidence performance risks:

Store the JSON artifact or pass it to a later CI reporting step. SARIF, pull-request annotations, baselines, and runtime query correlation are outside v0.1.1.

Architecture and extension points

The core pipeline is:

  1. FileDiscovery finds PHP files and applies exclusions.
  2. PhpFileParser parses source and resolves names.
  3. ModelMetadataResolver builds a compact model and Resource index.
  4. FlowAnalyzer tracks bounded provenance, assignments, branches, callbacks, loops, loading, and aggregates.
  5. RuleEngine dispatches typed analysis events to N1–N4 rules.
  6. FindingCollector deduplicates and sorts immutable findings.
  7. ConsoleReporter or JsonReporter renders the result.

The scanner retains only scan-local ASTs needed for both metadata and analysis. It does not persist a cache or run analysis in parallel.

The current public command and finding shape are intended to remain stable while future releases may add baselines, SARIF, route/runtime evidence, and query-count correlation.

Development and verification

Clone the repository and install development dependencies:

Run the complete local verification suite:

Generate benchmark fixtures:

The tests use isolated PHP fixtures. They parse fixture source without including it, and they do not require a database, migrations, factories, or HTTP requests.

When changing detection behavior, add both a candidate fixture and a safe/ambiguous fixture. Check deterministic ordering, JSON validity, exit codes, and whether the change affects confidence or severity.

Versioning and license

The package follows semantic versioning within the 0.x development series. The current release is v0.1.1; the immutable v0.1.0 tag remains available for the initial release.

The package is released under the MIT license. See CHANGELOG.md.


All versions of laravel-nplusone-scanner with dependencies

PHP Build Version
Package Version
Requires php Version ^8.2
illuminate/console Version ^12.0|^13.0
illuminate/support Version ^12.0|^13.0
nikic/php-parser Version ^5.0
symfony/console Version ^7.2|^8.0
symfony/finder Version ^7.2|^8.0
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package amrachraf6699/laravel-nplusone-scanner contains the following files

Loading the files please wait ...