Top Related Projects
A tool to automatically fix PHP Coding Standards issues
PHP Static Analysis Tool - discover bugs in your code without running it!
A static analysis tool for finding errors in PHP applications
⚗️ Adds code analysis to Laravel improving developer productivity and code quality.
A simple PHP API extension for DateTime.
The Laravel Framework.
Quick Overview
Laravel IDE Helper is a package designed to enhance the development experience for Laravel projects in IDEs. It generates helper files that provide better auto-completion, type hinting, and code navigation for Laravel facades, models, and other components. This tool bridges the gap between Laravel's dynamic nature and static analysis tools used by IDEs.
Pros
- Improves code completion and type hinting for Laravel projects
- Enhances IDE functionality for Laravel-specific features
- Supports multiple IDEs, including PhpStorm, VSCode, and Sublime Text
- Regularly updated to support the latest Laravel versions
Cons
- May require manual regeneration of helper files after significant code changes
- Can increase project size due to additional generated files
- Might cause confusion for developers not familiar with the concept of IDE helpers
- Some advanced Laravel features may still lack full IDE support
Code Examples
- Generate IDE helper files:
<?php
// Generate helper file for Laravel Facades
php artisan ide-helper:generate
// Generate helper file for models
php artisan ide-helper:models
// Generate PhpStorm meta file
php artisan ide-helper:meta
- Add IDE helper annotations to a model:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
/**
* @property int $id
* @property string $name
* @property \Carbon\Carbon $created_at
* @property \Carbon\Carbon $updated_at
*/
class User extends Model
{
// Model implementation
}
- Use IDE helper for better auto-completion with facades:
<?php
// Before IDE helper
Route::get('/', function () {
return view('welcome');
});
// After IDE helper
\Illuminate\Support\Facades\Route::get('/', function () {
return view('welcome');
});
Getting Started
-
Install the package via Composer:
composer require --dev barryvdh/laravel-ide-helper
-
Add the service provider to
config/app.php
(Laravel 5.4 and below):Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,
-
Generate the helper files:
php artisan ide-helper:generate php artisan ide-helper:meta
-
For model helpers, add the following to your
composer.json
:"scripts": { "post-update-cmd": [ "Illuminate\\Foundation\\ComposerScripts::postUpdate", "@php artisan ide-helper:generate", "@php artisan ide-helper:meta" ] }
-
Enjoy improved IDE support for your Laravel project!
Competitor Comparisons
A tool to automatically fix PHP Coding Standards issues
Pros of PHP-CS-Fixer
- Broader scope: Works with any PHP project, not limited to Laravel applications
- Extensive ruleset: Offers a wide range of coding style and formatting rules
- Highly configurable: Allows fine-tuning of rules to match specific project requirements
Cons of PHP-CS-Fixer
- Steeper learning curve: Requires more setup and configuration compared to Laravel IDE Helper
- No specific Laravel integration: Doesn't provide Laravel-specific features like model annotations
Code Comparison
Laravel IDE Helper:
<?php
/**
* @property int $id
* @property string $name
*/
class User extends Model
{
// ...
}
PHP-CS-Fixer:
<?php
$config = new PhpCsFixer\Config();
return $config->setRules([
'@PSR2' => true,
'array_syntax' => ['syntax' => 'short'],
'ordered_imports' => ['sort_algorithm' => 'alpha'],
]);
Laravel IDE Helper focuses on generating docblocks and annotations for better IDE support in Laravel projects. PHP-CS-Fixer, on the other hand, is a general-purpose tool for enforcing coding standards and fixing PHP code style issues across any PHP project. While Laravel IDE Helper enhances development experience specifically for Laravel, PHP-CS-Fixer ensures consistent code formatting and adherence to coding standards in a broader PHP ecosystem.
PHP Static Analysis Tool - discover bugs in your code without running it!
Pros of phpstan
- Language-agnostic static analysis tool, not limited to Laravel projects
- Offers more advanced type checking and error detection capabilities
- Can be integrated into various CI/CD pipelines for automated code quality checks
Cons of phpstan
- Steeper learning curve, especially for beginners
- Requires more configuration and setup compared to laravel-ide-helper
- May produce false positives in some cases, requiring manual intervention
Code Comparison
phpstan:
<?php
// phpstan.neon
parameters:
level: 5
paths:
- app
- tests
laravel-ide-helper:
<?php
// composer.json
"require-dev": {
"barryvdh/laravel-ide-helper": "^2.8"
}
Summary
phpstan is a powerful static analysis tool that offers advanced type checking and error detection across various PHP projects. It's highly configurable and can be integrated into CI/CD pipelines. However, it has a steeper learning curve and may require more setup than laravel-ide-helper.
laravel-ide-helper, on the other hand, is specifically designed for Laravel projects and provides excellent IDE support with minimal configuration. It's easier to set up and use, especially for Laravel developers, but lacks the advanced static analysis features of phpstan.
A static analysis tool for finding errors in PHP applications
Pros of Psalm
- Provides more comprehensive static analysis and type checking
- Offers advanced features like taint analysis and security checks
- Can be used with any PHP project, not limited to Laravel
Cons of Psalm
- Steeper learning curve and more complex configuration
- May generate more false positives, requiring fine-tuning
- Less focused on IDE integration compared to Laravel IDE Helper
Code Comparison
Laravel IDE Helper:
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
// Factory definition
});
Psalm:
<?php
/**
* @psalm-suppress MixedArgumentTypeCoercion
* @var \Illuminate\Database\Eloquent\Factory $factory
*/
$factory->define(App\User::class, function (Faker\Generator $faker): array {
// Factory definition with type hints
});
Laravel IDE Helper focuses on generating PHPDoc annotations for better IDE integration, while Psalm provides more detailed static analysis and type checking. Psalm's code often includes more specific type annotations and suppression comments to handle complex scenarios.
⚗️ Adds code analysis to Laravel improving developer productivity and code quality.
Pros of Larastan
- Provides static analysis for Laravel applications, catching potential errors before runtime
- Integrates seamlessly with PHPStan, offering a more comprehensive analysis
- Supports custom PHPStan rules and extensions
Cons of Larastan
- Steeper learning curve, especially for developers new to static analysis tools
- May produce false positives in some cases, requiring additional configuration
- Limited IDE integration compared to Laravel IDE Helper
Code Comparison
Laravel IDE Helper:
<?php
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
// Factory definition
});
Larastan:
<?php
use PHPStan\Testing\TestCase;
class ExampleTest extends TestCase
{
public function testExample(): void
{
$this->analyse([__DIR__ . '/data/file.php'], [
// Expected errors
]);
}
}
Both tools serve different purposes in the Laravel ecosystem. Laravel IDE Helper focuses on improving IDE autocompletion and type hinting, while Larastan provides static analysis for catching potential errors. Laravel IDE Helper is generally easier to set up and use, especially for beginners, but Larastan offers more advanced analysis capabilities for those willing to invest time in learning and configuring it.
A simple PHP API extension for DateTime.
Pros of Carbon
- Specialized for date and time manipulation, offering a rich set of methods
- Standalone library, can be used in any PHP project, not limited to Laravel
- Extensive localization support for multiple languages and regions
Cons of Carbon
- Focused solely on date/time operations, not providing general IDE assistance
- May require additional setup for IDE autocompletion in some environments
- Larger footprint if only basic date/time functionality is needed
Code Comparison
Carbon:
$date = Carbon::now()->addWeeks(2);
$formatted = $date->format('Y-m-d H:i:s');
$diffInDays = $date->diffInDays(Carbon::yesterday());
Laravel IDE Helper:
// No direct code comparison as it generates helper files
php artisan ide-helper:generate
php artisan ide-helper:models
Summary
Carbon is a powerful date and time manipulation library for PHP, offering extensive functionality for working with dates, times, and intervals. It's widely used across various PHP projects and frameworks.
Laravel IDE Helper, on the other hand, is specifically designed to enhance IDE support for Laravel applications. It generates helper files to improve autocompletion and type hinting for Laravel-specific code.
While both tools serve different purposes, they can be used together in Laravel projects to improve development experience and code quality.
The Laravel Framework.
Pros of Laravel Framework
- Comprehensive full-stack web application framework
- Extensive built-in features and tools for rapid development
- Large, active community and ecosystem
Cons of Laravel Framework
- Larger footprint and potential performance overhead
- Steeper learning curve for beginners
- May include unnecessary features for smaller projects
Code Comparison
Laravel Framework:
use Illuminate\Support\Facades\Route;
Route::get('/', function () {
return view('welcome');
});
Laravel IDE Helper:
/** @var \Illuminate\Database\Eloquent\Factory $factory */
$factory->define(App\User::class, function (Faker\Generator $faker) {
// Factory definition
});
Key Differences
Laravel Framework is a complete web application framework, while Laravel IDE Helper is a development tool specifically designed to enhance IDE functionality when working with Laravel projects. The IDE Helper provides better code completion, type hinting, and navigation for Laravel-specific code, which is not a primary focus of the main framework.
Laravel Framework offers a wide range of features for building web applications, including routing, database abstraction, authentication, and more. In contrast, Laravel IDE Helper focuses on improving the development experience by generating helper files that assist IDEs in understanding Laravel's dynamic nature.
While Laravel Framework is essential for building Laravel applications, Laravel IDE Helper is an optional tool that can significantly improve developer productivity, especially in larger projects or when using advanced IDE features.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual CopilotREADME
IDE Helper Generator for Laravel
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.
The 3.x branch supports Laravel 10 and 11. For older version, use the 2.x releases.
Installation
Require this package with composer using the following command:
composer require --dev barryvdh/laravel-ide-helper
[!NOTE]
If you encounter version conflicts with doctrine/dbal, please try:composer require --dev barryvdh/laravel-ide-helper --with-all-dependencies
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 incomposer.json
, e.g."extra": { "laravel": { "dont-discover": [ "barryvdh/laravel-ide-helper" ] } }
- Add the following class to the
providers
array inconfig/app.php
:
If you want to manually load it only in non-production environments, instead you can add this to yourBarryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class,
AppServiceProvider
with theregister()
method:public function register() { if ($this->app->isLocal()) { $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!
php artisan ide-helper:generate
- PHPDoc generation for Laravel Facadesphp artisan ide-helper:models
- PHPDocs for modelsphp artisan ide-helper:meta
- PhpStorm Meta file
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.
If you use real-time facades in your app, those will also be included in the generated file using a @mixin
annotation and extending the original class underneath the facade.
Note: this feature uses the generated real-time facades files in the storage/framework/cache
folder. Those files are generated on-demand as you use the real-time facade, so if the framework has not generated that first, it will not be included in the helper file. Run the route/command/code first and then regenerate the helper file and this time the real-time facade will be included in it.
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 PHPDoc generation for macros and mixins
This package can generate PHPDocs for macros and mixins which will be added to the _ide_helper.php
file.
But this only works if you use type hinting when declaring a macro.
Str::macro('concat', function(string $str1, string $str2) : string {
return $str1 . $str2;
});
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)
.
Alternatively using the --write-mixin (-M)
option will only add a mixin tag to your Model file,
writing the rest in (_ide_helper_models.php
).
The class name will be different from the model, avoiding the IDE duplicate annoyance.
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. It will not update changed properties/methods.
With the --reset (-R)
option, the whole existing PHPDoc is replaced, including any comments that have been made.
php artisan ide-helper:models "App\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)
* @method static \Illuminate\Database\Eloquent\Builder|\App\Models\Post forAuthors(\User ...$authors)
* â¦
*/
With the --write-mixin (-M)
option
/**
* â¦
* @mixin IdeHelperPost
*/
Model Directories
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 "App\Models\Post" "App\Models\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.
Ignore Models
Models can be ignored using the --ignore (-I)
option
php artisan ide-helper:models --ignore="App\Models\Post,App\Models\User"
Or can be ignored by setting the ignored_models
config
'ignored_models' => [
App\Post::class,
Api\User::class
],
Magic where*
methods
Eloquent allows calling where<Attribute>
on your models, 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
.
Generics annotations
Laravel 9 introduced generics annotations in DocBlocks for collections. PhpStorm 2022.3 and above support the use of generics annotations within @property
and @property-read
declarations in DocBlocks, e.g. Collection<User>
instead of Collection|User[]
.
These can be disabled by setting the config use_generics_annotations
to false
.
Support @comment
based on DocBlock
In order to better support IDEs, relations and getters/setters can also add a comment to a property like table columns. Therefore a custom docblock @comment
is used:
class Users extends Model
{
/**
* @comment Get User's full name
*
* @return string
*/
public function getFullNameAttribute(): string
{
return $this->first_name . ' ' .$this->last_name ;
}
}
// => after generate models
/**
* App\Models\Users
*
* @property-read string $full_name Get User's full name
* â¦
*/
Dedicated Eloquent Builder methods
A new method to the eloquent models was added called newEloquentBuilder
Reference where we can
add support for creating a new dedicated class instead of using local scopes in the model itself.
If for some reason it's undesired to have them generated (one for each column), you can disable this via config write_model_external_builder_methods
and setting it to false
.
Custom Relationship Types
If you are using relationships not built into Laravel you will need to specify the name and returning class in the config to get proper generation.
'additional_relation_types' => [
'externalHasMany' => \My\Package\externalHasMany::class
],
Found relationships will typically generate a return value based on the name of the relationship.
If your custom relationships don't follow this traditional naming scheme you can define its return type manually. The available options are many
and morphTo
.
'additional_relation_return_types' => [
'externalHasMultiple' => 'many'
],
Model Hooks
If you need additional information on your model from sources that are not handled by default, you can hook in to the
generation process with model hooks to add extra information on the fly.
Simply create a class that implements ModelHookInterface
and add it to the model_hooks
array in the config:
'model_hooks' => [
MyCustomHook::class,
],
The run
method will be called during generation for every model and receives the current running ModelsCommand
and the current Model
, e.g.:
class MyCustomHook implements ModelHookInterface
{
public function run(ModelsCommand $command, Model $model): void
{
if (! $model instanceof MyModel) {
return;
}
$command->setProperty('custom', 'string', true, false, 'My custom property');
$command->unsetMethod('method');
$command->setMethod('method', $command->getMethodType($model, '\Some\Class'), ['$param']);
}
}
/**
* MyModel
*
* @property integer $id
* @property-read string $custom
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 in 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 in your config/ide-helper.php
file.
Deprecated for Laravel 8 or latest.
'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 where you want to take advantage of PhpStorm's support of the directory .phpstorm.meta.php/
: all files placed there are parsed, should you want to provide additional files to PhpStorm.
License
The Laravel IDE Helper Generator is open-sourced software licensed under the MIT license
Top Related Projects
A tool to automatically fix PHP Coding Standards issues
PHP Static Analysis Tool - discover bugs in your code without running it!
A static analysis tool for finding errors in PHP applications
⚗️ Adds code analysis to Laravel improving developer productivity and code quality.
A simple PHP API extension for DateTime.
The Laravel Framework.
Convert designs to code with AI
Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.
Try Visual Copilot