Laravel IDE Helper

repository·master·Indexed 12 days ago

https://github.com/barryvdh/laravel-ide-helper

An IDE Helper Generator for Laravel that creates PHPDoc files to enable accurate autocompletion and code intelligence in IDEs like PhpStorm and VS Code. It provides commands to generate helper files for Laravel Facades (ide-helper:generate), Eloquent Models (ide-helper:models), and PhpStorm metadata for Container instances (ide-helper:meta). The 3.x branch supports Laravel 10 and later.

Tokens
4.9K
Snippets
21
Records
29
Agent score
97%

What's inside Laravel IDE Helper

  1. Overview of IDE Helper functionality

    master
    The laravel-ide-helper package generates helper files that enable your IDE (like PhpStorm or VS Code) to provide accurate autocompletion for Laravel-specific features. It generates PHPDocs directly from your project's source files, ensuring that the autocompletion remains up-to-date with your code.
  2. How PhpStorm Meta improves Container autocompletion

    master

    Once the meta file is generated, PhpStorm can map container keys to specific class types. This works for both string keys and class name arguments.

    Examples of supported patterns:

    • Resolving by key: app('events') or \App::make('events').
    • Resolving by class name: app('App\SomeClass') or app(App\SomeClass::class).
    • Working with type-hinted variables: /** @var \Illuminate\Foundation\Application $app */ $app->make('events')->fire();
    app('events')->fire();
    \App::make('events')->fire();
    
    /** @var \Illuminate\Foundation\Application $app */
    $app->make('events')->fire();
    
    // When the key is not found, it uses the argument as class name
    app('App\SomeClass');
    // Also works with
    app(App\SomeClass::class);
  3. Generate PHPDocs for macros and mixins

    master

    The package can add PHPDocs for macros and mixins to the _ide_helper.php file. For this to work, you must use type hinting when declaring the macro.

    Str::macro('concat', function(string $str1, string $str2) : string {
        return $str1 . $str2;
    });
  4. Generate autocompletion for Laravel Facades

    master

    Run the ide-helper:generate command to create an _ide_helper.php file. This file contains PHPDoc annotations for Laravel Facades, allowing your IDE to provide autocomplete for them.

    Key details:

    • The output filename can be customized in the filename config key.
    • If you use real-time facades, ensure you have actually triggered them in your application (e.g., by running a route) so the framework generates the necessary cache files before running this command.
    • If you lack a default database connection, use the -M option to use an in-memory SQLite driver.
    • You can include helper files (like Illuminate/Support/helpers.php) by using the --helpers (-H) option, though this is disabled by default.
    php artisan ide-helper:generate
  5. Generate PHPDocs for Laravel Fluent methods

    master

    To get IDE autocompletion for Fluent methods used in migrations (e.g., $table->string(...)->nullable()), enable the include_fluent option in config/ide-helper.php and then run the facade generator.

    ```php
    'include_fluent' => true,

    Then run:

    php artisan ide-helper:generate

  6. Automate IDE Helper generation via Composer

    master

    To ensure your IDE helper files stay up to date when dependencies change, add the generation commands to your composer.json scripts under post-update-cmd.

    "scripts": {
        "post-update-cmd": [
            "Illuminate\\Foundation\\ComposerScripts::postUpdate",
            "@php artisan ide-helper:generate",
            "@php artisan ide-helper:meta"
        ]
    },
  7. Configure Model scanning and ignoring

    master

    You can control which models are processed by the ide-helper:models command:

    • Specific Models: Pass model class names as arguments: php artisan ide-helper:models "App\Models\Post".
    • Custom Directory: Use the --dir option to scan a specific directory: php artisan ide-helper:models --dir="app/src/Model".
    • Ignore Models: Use the --ignore (-I) flag with a comma-separated list: php artisan ide-helper:models --ignore="App\Models\Post,App\Models\User". Alternatively, define them in the ignored_models array in your config file.
    php artisan ide-helper:models --dir="path/to/models"
    php artisan ide-helper:models --ignore="App\Models\Post,App\Models\User"
  8. Generate PHPDocs for Eloquent Models

    master

    The ide-helper:models command generates PHPDoc annotations for your models based on database columns, relationships, and getters/setters. This requires a working database connection.

    Writing strategies:

    • Write to models directly: Use --write (-W) to append properties/methods to your model files. Use --reset (-R) to replace existing PHPDocs entirely.
    • Separate file: By default, it creates _ide_helper_models.php.
    • Mixin approach: Use --write-mixin (-M) to add a @mixin tag to your model file while keeping the actual property definitions in a separate file. This prevents IDE duplicate warnings.
    • Minimal helper: Use --write-eloquent-helper (-E) to generate a small version of the helper required for QueryBuilder methods if you don't want the full _ide_helper.php.
    php artisan ide-helper:models -RW
  9. Generate PhpStorm Meta for Container instances

    master

    You can generate a .phpstorm.meta.php file to help PhpStorm understand which objects are being resolved from the Laravel IoC Container. This enables autocompletion for methods on objects returned by app() or App::make() based on their string keys (e.g., app('events') will autocomplete methods from Illuminate\Events\Dispatcher).

    Important Notes:

    • You may need to restart PhpStorm and ensure .phpstorm.meta.php is indexed for changes to take effect.
    • If you encounter a FatalException: class not found, check your Laravel configuration and remove unused services (e.g., remove S3 as a cloud driver if not configured, or remove RedisServiceProvider if not used).
    • You can customize the output filename using the meta_filename configuration key. This is useful if you want to use a directory-based meta approach (e.g., .phpstorm.meta.php/).
    php artisan ide-helper:meta
  10. Install the IDE Helper via Composer

    master

    To use the IDE Helper in your Laravel project, install it as a development dependency using Composer.

    Note: The 3.x branch supports Laravel 10 and later. For older Laravel versions, use the 2.x releases.

    composer require --dev barryvdh/laravel-ide-helper
  11. Understand how Model PHPDocs are generated

    master

    The ModelsCommand automates the creation of PHPDoc blocks for Eloquent models to improve IDE auto-completion. It handles several complex scenarios:

    Properties and Attributes

    • Database Columns: Generates @property tags for model attributes.
    • Accessors/Mutators: Detects getter and setter methods to define @property-read or @property-write tags.
    • Custom Casts: Inspects Laravel Casts (implementing CastsAttributes or Castable) to determine the correct type hint for attributes.

    Methods and Relations

    • Eloquent Relations: Generates @method tags for relationships (e.g., hasOne, belongsTo, morphTo), correctly identifying if they are nullable.
    • Soft Deletes: If a model uses SoftDeletes, it automatically adds @method tags for withTrashed(), withoutTrashed(), and onlyTrashed().
    • Factories: If the HasFactory trait is present, it adds a @method factory(...) tag.
    • Collections: For models returning custom collections, it generates type-hinted @method tags for get() and all() using generics or array syntax.

    Mixins and Writing

    • Writing to Files: The command can either overwrite the existing DocBlock in your model file or, if write_mixin is enabled, generate a separate mixin class (e.g., IdeHelperYourModel) to keep the original model file clean.