Want to take your software engineering career to the next level? Join the mailing list for career tips & advice Click here

laravel-ide-helper

Laravel IDE Helper

Star full 4f7b624809470f25b6493d5a7b30d9b9cb905931146e785d67c86ef0c205a402Star full 4f7b624809470f25b6493d5a7b30d9b9cb905931146e785d67c86ef0c205a402Star full 4f7b624809470f25b6493d5a7b30d9b9cb905931146e785d67c86ef0c205a402Star full 4f7b624809470f25b6493d5a7b30d9b9cb905931146e785d67c86ef0c205a402Star half bd79095782ee4930099175e5ce7f4c89fa3ddabcd56fffcc7c74f6f2a2d46b27 (1 ratings)
Rated 4.5 out of 5
Subscribe to updates I use laravel-ide-helper


Statistics on laravel-ide-helper

Number of watchers on Github 10228
Number of open issues 152
Average time to close an issue 15 days
Main language PHP
Average time to merge a PR 4 days
Open pull requests 81+
Closed pull requests 29+
Last commit 19 days ago
Repo Created over 7 years ago
Repo Last Updated 16 days ago
Size 937 KB
Organization / Authorbarryvdh
Latest Releasev2.7.0
Contributors41
Page Updated
Do you use laravel-ide-helper? Leave a review!
View open issues (152)
View laravel-ide-helper activity
View on github
Fresh, new opensource launches ๐Ÿš€๐Ÿš€๐Ÿš€
Software engineers: It's time to get promoted. Starting NOW! Subscribe to my mailing list and I will equip you with tools, tips and actionable advice to grow in your career.
Evaluating laravel-ide-helper for your project? Score Explanation
Commits Score (?)
Issues & PR Score (?)

Laravel IDE Helper Generator

Latest Version on Packagist Software License Build Status Total Downloads

Complete PHPDocs, directly from the source

This package generates helper files that enable your IDE to provide accurate autocompletion. Generation is done based on the files in your project, so they are always up-to-date.

Installation

Require this package with composer using the following command:

composer require --dev barryvdh/laravel-ide-helper

This package makes use of Laravels package auto-discovery mechanism, which means if you don't install dev dependencies in production, it also won't be loaded.

If for some reason you want manually control this:

  • add the package to the extra.laravel.dont-discover key in composer.json, e.g. json "extra": { "laravel": { "dont-discover": [ "barryvdh/laravel-ide-helper", ] } }
  • Add the following class to the providers array in config/app.php: php Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class, If you want to manually load it only in non-production environments, instead you can add this to your AppServiceProvider with the register() method: php public function register() { if ($this->app->environment() !== 'production') { $this->app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class); } // ... }

Note: Avoid caching the configuration in your development environment, it may cause issues after installing this package; respectively clear the cache beforehand via php artisan cache:clear if you encounter problems when running the commands

Usage

Check out this Laracasts video for a quick introduction/explanation!

Note: You do need CodeComplice for Sublime Text: https://github.com/spectacles/CodeComplice

Automatic PHPDoc generation for Laravel Facades

You can now re-generate the docs yourself (for future updates)

php artisan ide-helper:generate

Note: bootstrap/compiled.php has to be cleared first, so run php artisan clear-compiled before generating.

This will generate the file _ide_helper.php which is expected to be additionally parsed by your IDE for autocomplete. You can use the config filename to change its name.

You can configure your composer.json to do this each time you update your dependencies:

"scripts": {
    "post-update-cmd": [
        "Illuminate\\Foundation\\ComposerScripts::postUpdate",
        "@php artisan ide-helper:generate",
        "@php artisan ide-helper:meta"
    ]
},

You can also publish the config file to change implementations (ie. interface to specific class) or set defaults for --helpers.

php artisan vendor:publish --provider="Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider" --tag=config

The generator tries to identify the real class, but if it cannot be found, you can define it in the config file.

Some classes need a working database connection. If you do not have a default working connection, some facades will not be included. You can use an in-memory SQLite driver by adding the -M option.

You can choose to include helper files. This is not enabled by default, but you can override it with the --helpers (-H) option. The Illuminate/Support/helpers.php is already set up, but you can add/remove your own files in the config file.

Automatic PHPDocs for models

If you don't want to write your properties yourself, you can use the command php artisan ide-helper:models to generate PHPDocs, based on table columns, relations and getters/setters.

Note: this command requires a working database connection to introspect the table of each model

By default, you are asked to overwrite or write to a separate file (_ide_helper_models.php). You can write the comments directly to your Model file, using the --write (-W) option, or force to not write with --nowrite (-N).

Please make sure to back up your models, before writing the info.

Writing to the models should keep the existing comments and only append new properties/methods. The existing PHPDoc is replaced, or added if not found. With the --reset (-R) option, the existing PHPDocs are ignored, and only the newly found columns/relations are saved as PHPDocs.

php artisan ide-helper:models Post
/**
 * App\Models\Post
 *
 * @property integer $id
 * @property integer $author_id
 * @property string $title
 * @property string $text
 * @property \Illuminate\Support\Carbon $created_at
 * @property \Illuminate\Support\Carbon $updated_at
 * @property-read \User $author
 * @property-read \Illuminate\Database\Eloquent\Collection|\Comment[] $comments
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Post newModelQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Post newQuery()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Post query()
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Post whereTitle($value)
 * 
 */

By default, models in app/models are scanned. The optional argument tells what models to use (also outside app/models).

php artisan ide-helper:models Post User

You can also scan a different directory, using the --dir option (relative from the base path):

php artisan ide-helper:models --dir="path/to/models" --dir="app/src/Model"

You can publish the config file (php artisan vendor:publish) and set the default directories.

Models can be ignored using the --ignore (-I) option

php artisan ide-helper:models --ignore="Post,User"

Or can be ignored by setting the ignored_models config

'ignored_models' => [
    Post::class,
    Api\User::class
],

Note: With namespaces, wrap your model name in double-quotes ("): php artisan ide-helper:models "API\User", or escape the slashes (Api\\User).

Magic where* methods

Eloquent allows calling where<Attribute> on your modes, e.g. Post::whereTitle() and automatically translates this to e.g. Post::where('title', '=', '').

If for some reason it's undesired to have them generated (one for each column), you can disable this via config write_model_magic_where and setting it to false.

Magic *_count properties

You may use the ::withCount method to count the number results from a relationship without actually loading them. Those results are then placed in attributes following the <columname>_count convention.

By default, these attributes are generated in the phpdoc. You can turn them off by setting the config write_model_relation_count_properties to false.

Unsupported or custom database types

Common column types (e.g. varchar, integer) are correctly mapped to PHP types (string, int).

But sometimes you may want to use custom column types in your database like geography, jsonb, citext, bit, etc. which may throw an Unknown database type-Exception.

For those special cases, you can map them via the config custom_db_types. Example:

'custom_db_types' => [
    'mysql' => [
        'geography' => 'array',
        'point' => 'array',
    ],
    'postgresql' => [
        'jsonb' => 'string',
        '_int4' => 'array',
    ],
],

Automatic PHPDocs generation for Laravel Fluent methods

If you need PHPDocs support for Fluent methods in migration, for example

$table->string("somestring")->nullable()->index();

After publishing vendor, simply change the include_fluent line your config/ide-helper.php file into:

'include_fluent' => true,

Then run php artisan ide-helper:generate, you will now see all Fluent methods recognized by your IDE.

Auto-completion for factory builders

If you would like the factory()->create() and factory()->make() methods to return the correct model class, you can enable custom factory builders with the include_factory_builders line your config/ide-helper.php file.

'include_factory_builders' => true,

For this to work, you must also publish the PhpStorm Meta file (see below).

PhpStorm Meta for Container instances

It's possible to generate a PhpStorm meta file to add support for factory design pattern. For Laravel, this means we can make PhpStorm understand what kind of object we are resolving from the IoC Container. For example, events will return an Illuminate\Events\Dispatcher object, so with the meta file you can call app('events') and it will autocomplete the Dispatcher methods.

php artisan ide-helper:meta
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);

Note: You might need to restart PhpStorm and make sure .phpstorm.meta.php is indexed.

Note: When you receive a FatalException: class not found, check your config (for example, remove S3 as cloud driver when you don't have S3 configured. Remove Redis ServiceProvider when you don't use it).

You can change the generated filename via the config meta_filename. This can be useful for cases you want to take advantage the PhpStorm also supports the directory .phpstorm.meta.php/ which would parse any file places there, should your want provide additional files to PhpStorm.

Usage with Lumen

This package is focused on Laravel development, but it can also be used in Lumen with some workarounds. Because Lumen works a little different, as it is like a bare bone version of Laravel and the main configuration parameters are instead located in bootstrap/app.php, some alterations must be made.

Enabling Facades

While Laravel IDE Helper can generate automatically default Facades for code hinting, Lumen doesn't come with Facades activated. If you plan in using them, you must enable them under the Create The Application section, uncommenting this line:

// $app->withFacades();

From there, you should be able to use the create_alias() function to add additional Facades into your application.

Adding the Service Provider

You can install Laravel IDE Helper in app/Providers/AppServiceProvider.php, and uncommenting this line that registers the App Service Providers, so it can properly load.

// $app->register(App\Providers\AppServiceProvider::class);

If you are not using that line, that is usually handy to manage gracefully multiple Laravel/Lumen installations, you will have to add this line of code under the Register Service Providers section of your bootstrap/app.php.

if ($app->environment() !== 'production') {
    $app->register(\Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class);
}

After that, Laravel IDE Helper should work correctly. During the generation process, the script may throw exceptions saying that some Class(s) doesn't exist or there are some undefined indexes. This is normal, as Lumen has some default packages stripped away, like Cookies, Storage and Session. If you plan to add these packages, you will have to add them manually and create additional Facades if needed.

Adding Additional Facades

Currently, Lumen IDE Helper doesn't take into account additional Facades created under bootstrap/app.php using create_alias(), so you need to create a config/app.php file and add your custom aliases under an aliases array again, like so:

return [
    'aliases' => [
        'CustomAliasOne' => Example\Support\Facades\CustomAliasOne::class,
        'CustomAliasTwo' => Example\Support\Facades\CustomAliasTwo::class,
        //...
    ]
];

After you run php artisan ide-helper:generate, it's recommended (but not mandatory) to rename config/app.php to something else, until you have to re-generate the docs or after passing to production environment. Lumen 5.1+ will read this file for configuration parameters if it is present, and may overlap some configurations if it is completely populated.

License

The Laravel IDE Helper Generator is open-sourced software licensed under the MIT license

laravel-ide-helper open issues Ask a question     (View All Issues)
  • over 3 years Error detection method
  • almost 4 years static called as dynamic warning on facade returning $this
  • almost 4 years Fatal error: Class 'Memcached' not found
  • almost 4 years Problem with Laravel 5.3 Models
  • almost 4 years Gate facade not generated in Lumen
  • almost 4 years class '' not found
  • almost 4 years Route parameters() breaks generate
  • almost 4 years Laravel 5.3 - Broadcast Facade autocompletion missing
  • almost 4 years Redis
  • almost 4 years Ability to write int and not integer.
  • about 4 years include SoftDeletes trait location?
  • about 4 years Using laravel-ide-helper in non-laravel project
  • about 4 years Unnecessary fully qualified model name
  • about 4 years custom helper functions not poped
  • about 4 years Feature request: Write PhpDoc directly to Laravel source code
  • about 4 years generates _ide_helper.php in executing directory not in project dir
  • about 4 years Shall 'static' means the child class is better ?
  • about 4 years ide-helper doesn't generate added Facades (Lumen)
  • about 4 years generate model phpDocs no property and method
  • about 4 years Can this work with Visual Studio Code?
  • about 4 years Route::auth is missed
  • about 4 years Did i can not generate the static function whereSomeField()
  • about 4 years Error when installing
  • about 4 years FatalErrorException
  • about 4 years Method not found in PhpStorm
  • over 4 years :meta & spark.laravel.com?
  • over 4 years Generate Entrust model docs
  • over 4 years segmentation fault in "ide-helper:model"
  • over 4 years Allow custom text to be added into phpstorm.meta.php during/after generation.
  • over 4 years Blade::directive method does not exist
laravel-ide-helper open pull requests (View All Pulls)
  • Add extend \Eloquent for ide-helper:models command
  • PHPDoc for Fluent methods commonly used in migrations
  • Refactoring Code
  • This is only used while developing
  • morphOne and morphTo fixes
  • add bin in composer
  • Meta command: Support aliases and instances in service container + option to set methods to access container
  • Eloquent mixin
  • Support for using namespaced models in relations (L5)
  • Allow for camel case model properties.
  • Look for additional facade aliases in app config array
  • fix reflection-docblock issue #352
  • An --> A
  • add autocomplete for Facade classes
  • Support for MSSQL tables not in the 'dbo' schema
  • Multi auth guards and multi auth providers compatibility
  • Adds support for macros
  • Reversing order of default facade list
  • Use short array syntax in configuration file
  • Generate standalone metafile or use new meta folder option.
  • Updated installation on fresh Lumen 5.4
  • add aliases to meta
  • removed static declaration
  • Fix autocompletion of methods declared in facades
  • Readme [Lumen]: Simpler solution for supporting additional Facades and a note on getting Eloquent mixin to work.
  • Small fix readme
  • Don't use Facade alias but actual class
  • Added check for Variadic
  • Added Validator and Gate facades for Lumen
  • Sort keys for generating stable .phpstorm.meta.php
  • Update license year
  • Use Illuminate\Support\Carbon instead of Carbon\Carbon
  • Ignore models by default
  • Keep "null"-ness of column even with model casts
  • Eloquent: Write docblocks even if no original found
  • Support for ::fake() calls
  • Changed overwriting confirmation message
  • Follow @mixin tags for Facade roots
  • Add notice about "Package Auto-Discovery" to docs
  • The 'artisan optimize' command is now deprecated.
  • Refactored internal code
  • Fix magic method generation & helper class aliases
  • Remove static on forceDelete and restore to prevent the methods to beโ€ฆ
  • Composer
  • readme update
  • Camel case setting mutators
  • Add configurable Formatter Control tags around model docblocks
  • Support php's array callable format for macro's.
  • Add DocBlocks for classes too
  • Allow for configurable helper of eloquent namespace
  • Allow command to find and use pivot models
  • Implement unit-tests for all source code to release v1.11.7
  • Remove Eloquent Model Helper from generate command
  • Add morphedByMany relationship
  • "smart-reset": Reset properties/methods, but keep the text
  • Add the option to hide the generated datetime from the generated files
  • Add model property types to magic where methods.
  • Created a positiblity to add custom relation type
  • Fix phpdoc generate for custom cast with parameter
  • [TEST] Show that custom phpdoc tags without space afterwards are unexpectedly changed
  • Support database.schema.table in \Illuminate\Database\Eloquent\Model::$table
  • GHA Composer v2
  • Fix class namespaces from uses
  • Model hooks
  • #938 Replaced assertRegExp() with assertMatchesRegularExpression
  • Fixed error reading dynamic properties
  • Implement DeferrableProvider
  • newModelQuery and newQuery can't be called statically
  • Change $this->app->environment() !== 'production' to $this->app->isLocal()
  • Restore original event dispatcher after Event::fake()
  • Stop calling a method static if its not static
  • Builder ไปŽ model ไธญ่Žทๅ–๏ผŒไธ‡ไธ€ๆœ‰ไบบไฟฎๆ”นไบ† model ่‡ชๅธฆ็š„ builder ๅ‘ข๏ผ
  • Automatically generate helpers
  • Fix non-facade classes will result in no autocomplete
  • Update ModelsCommand.php
  • Update Generator.php
  • Form request helpers
  • Fix issue 784 `Arr` and `Str` no autocomplete.
  • Pgsql schema in table name supports
  • Resolves view factory only at services' construction time
  • New --write-mixin option.
laravel-ide-helper questions on Stackoverflow (View All Questions)
  • Laravel IDE Helper Not Working After Upgrade PhpStorm 10
  • Problems with laravel-ide-helper
  • Laravel 5.1: Using the Laravel IDE Helper Generator in PhpStorm
  • Laravel 5 : Why is there a lot of dependencies to download when installing laravel-ide-helper?
  • Having trouble installing barryvdh/laravel-ide-helper via composer - class not found error in Laravel 4 project
laravel-ide-helper list of languages used
laravel-ide-helper latest release notes

Lots of tweaks/improvements, big thanks to @mfn for the help and bringing the Test Suite up to date!

  • Generate noinspections PHPStorm tags (option) #905
  • Added support for Laravel 7 custom casts #913
  • Ability to use patterns for model_locations #921
  • Prevent generation of invalid code for certain parameter default values #901
  • Infer return type from reflection if no phpdoc given #906
  • if a model implements interfaces, include them in the stub #920
  • fix: unregister meta command custom autoloader when it is no longer needed #919
  • Remove unnecessary and wrong definition of SoftDelete methods #918
  • Add custom collection support for get and all methods #903
  • Make hasOne and morphOne nullable. #864
  • Add ignored_models as config option #890
  • Fix camelCase duplicated properties generator. #881
Other projects in PHP