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 Create a minimal config file in your project root:

    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 Execute analysis:

    ./vendor/bin/phpstan analyse
    

    For memory-intensive projects, increase memory:

    ./vendor/bin/phpstan analyse --memory-limit=2G
    

First Use Case: Catching Undefined Methods

Larastan excels at detecting Laravel-specific issues like:

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

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

Implementation Patterns

1. Integration with CI/CD

Add Larastan to your GitHub Actions workflow:

- name: Run Larastan
  run: ./vendor/bin/phpstan analyse --level=7

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

2. Gradual Adoption

  • Start with level: 5 (moderate) to avoid overwhelming the team.
  • Generate a baseline for legacy code:
    ./vendor/bin/phpstan analyse --generate-baseline
    
    Commit phpstan.baseline.neon to track progress.

3. Custom PHPDoc Types

Leverage Larastan’s Laravel-specific PHPDoc types:

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

4. Rule-Specific Workflows

  • Database Rules: Enable enableMigrationCache in phpstan.neon to speed up analysis:
    parameters:
        larastan:
            enableMigrationCache: true
    
  • Translation Rules: Use NoMissingTranslationsRule to catch missing Blade translations:
    parameters:
        larastan:
            rules:
                - NoMissingTranslationsRule
    

5. IDE Integration


Gotchas and Tips

Common Pitfalls

  1. Memory Limits

    • Issue: Large codebases may hit memory limits.
    • Fix: Use --memory-limit=4G or split analysis by directory:
      ./vendor/bin/phpstan analyse app/Http app/Models
      
  2. False Positives in Magic Methods

    • Issue: Larastan may flag Laravel’s dynamic methods (e.g., Model::findOrFail()).
    • Fix: Ignore specific errors in phpstan.neon:
      parameters:
          ignoreErrors:
              - '#Call to undefined method .*findOrFail\(\)#'
      
  3. Migration Parsing Errors

    • Issue: Complex SQL in squashed migrations may fail.
    • Fix: Install phpmyadmin/sql-parser (GPL-licensed) for better support:
      composer require --dev phpmyadmin/sql-parser
      
  4. Template Types in Models

    • Issue: Generic model properties (e.g., Model<T>) may cause errors.
    • Fix: Use @template-extends in PHPDoc:
      /**
       * @template T of \Illuminate\Database\Eloquent\Model
       * @property T $relation
       */
      

Debugging Tips

  • Verbose Output: Run with --verbose to debug rule application:
    ./vendor/bin/phpstan analyse --verbose
    
  • Isolate Errors: Use --focus to target specific files/classes:
    ./vendor/bin/phpstan analyse --focus=app/Http/Controllers/UserController.php
    

Extension Points

  1. Custom Rules Extend Larastan by creating a PHPStan rule and include it in extension.neon:

    includes:
        - vendor/larastan/larastan/extension.neon
        - custom-rules.neon
    
  2. Override Default Config Use parameters.larastan to tweak behavior:

    parameters:
        larastan:
            parseModelCastsMethod: true  # Improves cast inference
            enableMigrationCache: false  # Disable if migrations are unstable
    
  3. Stub Files Add custom stubs for unsupported classes (e.g., third-party packages) in stubs/ and reference them in extension.neon:

    services:
        - MyCustomStub()
    

Pro Tips

  • Pair with pestphp/pest: Use Larastan’s rules to guide test writing:
    // Larastan catches this before you write tests:
    // ❌ $user->role->permissions->where('id', 1); // role() may return null
    
  • Leverage collection-of Type Reduce boilerplate for collections:
    /**
     * @return collection-of<\App\Models\User>
     */
    public function search(string $query): Collection
    
  • Monitor Progress Track error counts over time to measure code quality improvements:
    ./vendor/bin/phpstan analyse --count-errors
    
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.
codraw/framework-extra-bundle
codraw/messenger
codraw/security
codraw/mailer
codraw/contracts
codraw/profiling
codraw/dependency-injection
codraw/tester
codraw/core
nexmo/api-specification
capell-app/block-library
axium/identity
cetria/laravel-dummy-models
cetria/reflection-helper
agropredict/sso-auth-bundle
evolvestudio/spam-protection
datacore/hub-sdk
develia/commons
cuci/prototurk-sdk
cuci/prototurk-sdk-symfony