Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Larastan Laravel Package

nunomaduro/larastan

Larastan is a PHPStan extension for Laravel that adds strong type inference and “code analysis” by booting the app container. It understands Laravel’s magic, finds bugs early, and improves code quality and developer productivity.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require --dev larastan/larastan:^3.0
    

    Ensure your project uses PHP 8.2+ and Laravel 11.15+.

  2. Configure phpstan.neon: Place this in your project root (or copy from vendor/larastan/larastan/extension.neon):

    includes:
        - vendor/larastan/larastan/extension.neon
        - vendor/nesbot/carbon/extension.neon
    
    parameters:
        paths:
            - app/
        level: 5  # Start with level 5 (moderate strictness)
    
  3. First Run:

    ./vendor/bin/phpstan analyse
    

    For memory-heavy projects, add --memory-limit=2G.

First Use Case: Catching Undefined Method Calls

Larastan excels at flagging Laravel-specific issues like:

// ❌ Error: Call to undefined method `User::findByEmail()`
$user = User::findByEmail($email);

// ✅ Fix: Use `where()` or `find()` instead
$user = User::where('email', $email)->first();

Implementation Patterns

1. Daily Workflow Integration

  • Pre-Commit Hook: Add Larastan to your CI/CD pipeline or Git hooks (e.g., husky):

    ./vendor/bin/phpstan analyse --level=5 --error-format=github
    

    Use --error-format=github for PR-friendly output.

  • Incremental Analysis: Focus on one file/directory at a time:

    ./vendor/bin/phpstan analyse app/Http/Controllers --level=8
    

2. Leveraging Laravel-Specific Rules

  • Model Casting: Larastan infers cast types automatically. For custom casts, use @method PHPDoc:

    /**
     * @method static self whereActive(bool $value)
     * @phpstan-return self
     */
    
  • Query Builder: Avoid undefined methods like orderByRaw() without arguments:

    // ❌ Error: Missing SQL in `orderByRaw()`
    $users = User::orderByRaw(); // Fails
    
    // ✅ Fix
    $users = User::orderByRaw('created_at DESC');
    
  • Service Container: Resolve bindings with @var hints:

    /** @var \Illuminate\Contracts\Auth\Factory $auth */
    $auth = app(\Illuminate\Contracts\Auth\Factory::class);
    

3. Custom PHPDoc Types

Use Larastan’s custom types to improve type safety:

/**
 * @param \Laravel\Fortify\Contracts\CreatesNewUsers $guard
 */
public function register(CreatesNewUsers $guard) { ... }

/**
 * @return \Illuminate\Support\Collection<int, \App\Models\User>
 */
public function getActiveUsers(): Collection { ... }

4. Migration Analysis

Larastan parses migrations to infer column types:

// ✅ Auto-detected: `$user->email` is `string`
Schema::create('users', function (Blueprint $table) {
    $table->string('email');
});

Gotchas and Tips

Common Pitfalls

  1. False Positives in Dynamic Code:

    • Issue: Larastan may flag app() or config() calls as "undefined."
    • Fix: Use @var hints or @phpstan-ignore-line:
      /** @var \Illuminate\Config\Repository $config */
      $config = config('app.timezone');
      
  2. Blade Template Errors:

    • Issue: Missing translations or undefined Blade directives.
    • Fix: Enable NoMissingTranslationsRule in phpstan.neon:
      parameters:
          larastan:
              rules:
                  no_missing_translations: true
      
  3. Memory Limits:

    • Issue: Large codebases hit memory limits.
    • Fix: Use --memory-limit=4G or analyze files incrementally.
  4. Squashed Migrations:

    • Issue: Complex SQL may not parse correctly.
    • Fix: Install phpmyadmin/sql-parser (optional) for better support:
      composer require --dev phpmyadmin/sql-parser
      

Debugging Tips

  • Verbose Output:
    ./vendor/bin/phpstan analyse --verbose
    
  • Baseline File: For legacy codebases, generate a baseline to ignore existing errors:
    ./vendor/bin/phpstan analyse --generate-baseline
    
    Then commit phpstan.baseline.neon to version control.

Extension Points

  1. Custom Rules: Extend Larastan by creating a custom PHPStan rule (see PHPStan docs).

  2. Override Config: Disable specific rules in phpstan.neon:

    parameters:
        larastan:
            rules:
                no_undefined_model_methods: false
    
  3. Performance:

    • Enable enableMigrationCache to speed up repeated runs:
      parameters:
          larastan:
              enableMigrationCache: true
      

Pro Tips

  • Pair with phpstan-baseline: Use phpstan-baseline to track progress:
    composer require --dev phpstan/phpstan-baseline
    ./vendor/bin/phpstan analyse --baseline=phpstan.baseline.neon
    
  • IDE Integration: Configure your IDE (PHPStorm/VSCode) to run Larastan on save via settings.json:
    {
        "phpstan.executablePath": "./vendor/bin/phpstan",
        "phpstan.arguments": ["analyse", "--level=5"]
    }
    
  • CI/CD Badges: Add a PHPStan status badge to your README.md:
    [![PHPStan](https://github.com/your-repo/actions/workflows/phpstan.yml/badge.svg)](https://github.com/your-repo/actions/workflows/phpstan.yml)
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
hexters/coinpayment
rjcodes/rjcms
act-training/laravel-permissions-manager
alimarchal/laravel-chart-of-accounts
babenkoivan/elastic-scout-driver
mkwebdesign/filament-watchdog-v5
renatomarinho/laravel-page-speed
zedmagdy/filament-business-hours
renatovdemoura/blade-elements-ui
devgeek/beacon-admin
benjamin-rqt/data-watcher-bundle
atriumphp/atrium
sandermuller/package-boost-laravel
sandermuller/boost-skills
redaxo/core
yusufgenc/filament-api-forge
l3aro/rating-star-for-filament
leek/filament-subtenant-scope
anil/file-picker
broqit/fields-ai