Laravel IDE Helper

Overview

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.
    "extra": {
      "laravel": {
        "dont-discover": [
          "barryvdh/laravel-ide-helper"
        ]
      }
    }
  • Add the following class to the providers array in config/app.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:
    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!

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 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. 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 "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)
 * …
 */

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.

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.

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',
    ],
],

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 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. 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 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

Comments
  • Do you plan to release branch for lumen?

    Do you plan to release branch for lumen?

    Hi, Barry, I very like ide-helper and it would be cool to have a branch for lumen, that ready to work out of the box, or may be some manual of how to migrate with current version

    opened by likerRr 59
  • ISSUE :: Model Static Classes ... continuing issue

    ISSUE :: Model Static Classes ... continuing issue

    There is an update to Laravel 5.4 that makes the relations more clear to all (should be in v5.4.29) https://github.com/laravel/framework/commit/77d8c23fed764e6a38cc8608c28f0ad7c39deee4

    The only problem is that the helper @mixin \Eloquent needs to move to the Model class in order to work with the magic static methods properly https://github.com/laravel/framework/pull/20044/files

    Note ... you should no longer have to add that to each instance of a Model. It works with just the static definitions on the Model class.

    opened by Artistan 39
  • Error when installing

    Error when installing

    I'm using a frsh install of Laravel 5.2.36. When I run this command:

    composer require barryvdh/laravel-ide-helper

    I get the following error:

    Your requirements could not be resolved to an installable set of packages. Problem 1 - Installation request for phpdocumentor/reflection-docblock (locked at 3.0.2) -> satisfiable by phpdocumentor/reflection-docblock[3.0.2]. - barryvdh/laravel-ide-helper v2.1.0 requires phpdocumentor/reflection-docblock 2.0.4 -> satisfiable by phpdocumentor/reflection-docblock[2.0.4]. - barryvdh/laravel-ide-helper v2.1.1 requires phpdocumentor/reflection-docblock 2.0.4 -> satisfiable by phpdocumentor/reflection-docblock[2.0.4]. - barryvdh/laravel-ide-helper v2.1.2 requires phpdocumentor/reflection-docblock 2.0.4 -> satisfiable by phpdocumentor/reflection-docblock[2.0.4]. - barryvdh/laravel-ide-helper v2.1.3 requires phpdocumentor/reflection-docblock ^2.0.4 -> satisfiable by phpdocumentor/reflection-docblock[2.0.4]. - barryvdh/laravel-ide-helper v2.1.4 requires phpdocumentor/reflection-docblock ^2.0.4 -> satisfiable by phpdocumentor/reflection-docblock[2.0.4]. - Conclusion: don't install phpdocumentor/reflection-docblock 2.0.4 - Installation request for barryvdh/laravel-ide-helper ^2.1 -> satisfiable by barryvdh/laravel-ide-helper[v2.1.0, v2.1.1, v2.1.2, v2.1.3, v2.1.4].

    opened by showFocus 32
  • _ide_helper.php break the autocomplete in PHPStorm

    _ide_helper.php break the autocomplete in PHPStorm

    when i update to Laravel v5.4.12 i use IDE Helper v2.2 ( i update it to the Dev Version v2.3.0 still the same )

    only when i delete the "_ide_helper.php" the autocomplete works fine.

    only .phpstorm.meta.php & _ide_helper_models.php works fine

    opened by Coldzer0 29
  • .phpstorm.meta.php has no effect in PhpStorm 2016.1

    .phpstorm.meta.php has no effect in PhpStorm 2016.1

    @barryvdh , after a month or so, when I return to my project, for some weird reason, the generated .phpstorm.meta.php file is missing a lot of lines in it (such as lines for app('log'), app('validator') etc). My current file looks like this:

    https://gist.github.com/shehi/1aeb5d96c5c1b338360474efbd7806f0

    Has something changed with package?

    opened by shehi 29
  • Exception: Class auth does not exist

    Exception: Class auth does not exist

    composer.json:

    "barryvdh/laravel-ide-helper": "1.*"
    

    and got this message below:

    ➜  src  php artisan ide-helper:generate
    Exception: Class auth does not exist
    Skipping Illuminate\Support\Facades\Auth.
    Exception: Class auth does not exist
    Skipping Illuminate\Support\Facades\Password.
    A new helper file was written to _ide_helper.php
    
    opened by voidman 28
  • Lumen Fresh Install - Class 'League\Flysystem\Adapter\Local' not found

    Lumen Fresh Install - Class 'League\Flysystem\Adapter\Local' not found

    Hello,

    I get this error with a fresh install of Lumen (latest version - 5.7.4):

    > php artisan ide-helper:generate
    In FilesystemManager.php line 160:
      Class 'League\Flysystem\Adapter\Local' not found
    

    Any idea why? No filesystem config options are set.

    If I install league/flysystem package then this comes up:

    > php artisan ide-helper:generate
    In Alias.php line 69:
      Class App does not exist
    
    stale 
    opened by dciancu 27
  • Method with same name already defined in this class

    Method with same name already defined in this class

    L5.7.2, LIDEH:2.5.1 _ide_helper.php produces error in PHPStorm : 'Method with same name already defined in this class' on many methods. Never had an issue with 5.6, but this is the first time I'm installing both 5.7 Laravel and 2.5.1 LIDEH. Screenshot shows the first part of the file with underlined methods that reflect this error. image

    stale 
    opened by realmarkcross 26
  • Method where not found in App\Model

    Method where not found in App\Model

    Model::where()
    

    Results in the error "method where not found in App\Model"

    Laravel 5.7 laravel-ide-helper ^2.4 php 7.2.8

    I tried

    php artisan clear-compiled
    php artisan ide-helper:generate
    php artisan ide-helper:meta
    

    If I do

    Model::query()->where()
    

    It works fine

    stale 
    opened by quantumwebco 25
  • Unexpected no document

    Unexpected no document

    This started happening a few weeks ago, can't figure out why or how to correct.

    php artisan ide-helper:generate Unexpected no document on Illuminate\Database\Eloquent\Model Content did not change <?php

    namespace Illuminate\Database\Eloquent;

    use Exception; use ArrayAccess; use JsonSerializable; use Illuminate\Support\Arr; use Illuminate\Support\Str; use Illuminate\Contracts\Support\Jsonable; use Illuminate\Contracts\Support\Arrayable; use Illuminate\Contracts\Routing\UrlRoutable; use Illuminate\Contracts\Queue\QueueableEntity;

    opened by wayne5w 25
  • "artisan ide-helper:models --nowrite" gives "Multiple definitions exist for class ..."

    First off, thanks for a great package!

    After some hassle, I've got the facades and Eloquent/Builder stuff working like a charm.

    But I'm struggling a bit now with the Model helpers. I'd prefer them in the separate _ide_helper_models.php. But if I do so, PhpStorm finds both the original Model and the generated helper. How do I prevent that?

    stale 
    opened by johnvt 23
  • Property type isn't detected when casting Eloquent attributes to `spatie/laravel-data` Data objects

    Property type isn't detected when casting Eloquent attributes to `spatie/laravel-data` Data objects

    The problem

    When casting Eloquent attributes to spatie/laravel-data Data objects, ide-helper doesn't pick the correct class. For example, the example from Spatie's documentation https://spatie.be/docs/laravel-data/v2/advanced-usage/eloquent-casting:

    <?php
    # app/Models/Song.php
    namespace App\Models;
    
    use App\SpatieData\ArtistData;
    use Illuminate\Database\Eloquent\Model;
    
    class Song extends Model
    {
        protected $casts = [
            'artist' => ArtistData::class,
        ];
    }
    
    <?php
    # app/SpatieData/ArtistData.php
    namespace App\SpatieData;
    
    use Spatie\LaravelData\Data;
    
    class ArtistData extends Data
    {
        public function __construct(
            public string $name,
            public int $age,
        ) {
        }
    }
    

    Running php artisan ide-helper:models --dir='app' --write generates this DocBlock:

    /**
     * App\Models\Song
     *
     * @property \Spatie\LaravelData\Contracts\BaseData|null $artist // ❌ not the desired prop definition
     * @method static \Illuminate\Database\Eloquent\Builder|Song newModelQuery()
     * @method static \Illuminate\Database\Eloquent\Builder|Song newQuery()
     * @method static \Illuminate\Database\Eloquent\Builder|Song query()
     * @mixin \Eloquent
     */
    

    This means that we don't get the benefit of type-hinting for casted attributes like this:

    $songModel->artist->name;
    

    Why does this happen?

    This happens because src/Support/EloquentCasts/DataEloquentCast.php from Spatie's package specifies a return type. This is what ide-helper picks up:

    # src/Support/EloquentCasts/DataEloquentCast.php in spatie/laravel-data
    …
        public function get($model, string $key, $value, array $attributes): ?BaseData
        {
    …
    

    Proposed change

    I put this together when looking through the code, trying to work out how to fix it in a project of mine. I thought I'd turn it into a PR for discussion…

    This PR lets you instruct ide-helper to use the class that was specified, by adding the DocBlock tag @ide-helper-eloquent-cast-to-specified-class to the class being cast to. e.g.

    <?php
    # app/SpatieData/ArtistData.php
    
    /**
     * @ide-helper-eloquent-cast-to-specified-class
     */
    class ArtistData extends Data
    {
    …
    

    From which, ide-helper now generates:

    /**
     * App\Models\Song
     *
     * @property ArtistData $artist // ✅ the desired prop definition
     * @method static \Illuminate\Database\Eloquent\Builder|Song newModelQuery()
     * @method static \Illuminate\Database\Eloquent\Builder|Song newQuery()
     * @method static \Illuminate\Database\Eloquent\Builder|Song query()
     * @mixin \Eloquent
     */
    

    Notes

    • The @ide-helper-eloquent-cast-to-specified-class tag can be added to a class, or any of it's parents.
    • spatie/laravel-data could add this tag to their Spatie\LaravelData\Data class, so it's always applied to Data classes that use it. But if they don't, it can just as easily be added to Data classes (or a parent class) in individual projects.
    • This solution isn't specific to spatie/laravel-data. It can be used for any classes being cast to in this manner.

    Thoughts

    • I couldn't think of a way for it to happen automatically without forcing it in every case. Which I don't think is 100% desired.
    • I don't think having to add a @tag is a "nice" solution, however it does give control over when it happens.
    • An alternative I considered was to specify the relevant classes inside ide-helper's config file. But this doesn't seem very flexible.
    • I'd be interested to hear if anybody has other ideas about how to detect when it should occur.

    Other issues and PRs

    • This PR may help address this issue https://github.com/barryvdh/laravel-ide-helper/issues/1312
    • The https://github.com/barryvdh/laravel-ide-helper/pull/1388 PR addresses a slightly different situation. It falls back to the specified-class when none was specified by the casting class. It is short and elegant. However spatie/laravel-data does specify a return type. So whilst it might be a useful change, it doesn't affect this situation.
    • The comment https://github.com/barryvdh/laravel-ide-helper/issues/1312#issuecomment-1221270878 suggests hard-coding a check for spatie/laravel-data. This seems inflexible to me as it wouldn't allow for other packages or custom classes to benefit.

    Type of change

    • [ ] Bug fix (non-breaking change which fixes an issue)
    • [X] New feature (non-breaking change which adds functionality)
    • [ ] Breaking change (fix or feature that would cause existing functionality to not work as expected)
    • [ ] This change requires a documentation update
    • [ ] Misc. change (internal, infrastructure, maintenance, etc.)

    Checklist

    • [X] Existing tests have been adapted and/or new tests have been added
    • [X] Add a CHANGELOG.md entry
    • [ ] Update the README.md
    • [X] Code style has been fixed via composer fix-style
    opened by code-distortion 0
  • Improve formatting, readability and size of generated files.

    Improve formatting, readability and size of generated files.

    Versions:

    • ide-helper Version: v2.12.3
    • Laravel Version: v9.34.0
    • PHP Version: 8.1.11

    Summary:

    The generated _ide_helper.php file has inconsistent indentation among other things that both reduce readability and increase filesize. I would like to recommend enabling the rendering of whitespaces when working on this enhancement.

    Examples from the generated _ide_helper.php file:

    line 15 t/m 32

        namespace Illuminate\Support\Facades { 
                /**
         * 
         *
         * @see \Illuminate\Contracts\Foundation\Application
         */ 
            class App {
                        /**
             * Get the version number of the application.
             *
             * @return string 
             * @static 
             */ 
            public static function version()
            {
                            /** @var \Illuminate\Foundation\Application $instance */
                            return $instance->version();
            }
    

    Line 15031 t/m 15033

            public static function prepend($path, $data, $separator = '
    ')
            {
    

    Line 17217 t/m 17240

        namespace Illuminate\Support { 
                /**
         * 
         *
         */ 
            class Arr {
             
        }
                /**
         * 
         *
         */ 
            class Js {
             
        }
                /**
         * 
         *
         */ 
            class Str {
             
        }
         
    }
    

    Potential improvements:

    • Ensure proper indentation
    • Render special characters in parameters as an escaped character (' ' -> "\t") or their predefined constant. (PHP_EOL)
    • Remove empty docblocks
    • Prune trailing whitespaces
    • Convert spaces to tabs
    • Remove the @static tag as the functions themselves are already marked in their definition as a public static function
    • Remove double spaces in, and spaces that can interfere with, definitions (@param \Illuminate\Foundation\(callable(string, string, ?array, ?array): array)|array $attributes is incorrectly proccessed as type \Illuminate\Foundation\ (callable(string, with comment string, ?array, ?array): array)|array $attributes)
    enhancement 
    opened by S-K-Tiger 0
  • Analyzing custom facades without registering aliases

    Analyzing custom facades without registering aliases

    Versions:

    • ide-helper Version: 2.6
    • Laravel Version: 9.0
    • PHP Version: 8.1.12

    Question:

    Hi! Thanks for this package, I am wondering if I can get my custom Facade's methods to be added to _ide_helper.php without having to register it as an alias (I prefer to reference the full namespace instead of the alias) in config/app.php?

    So for example I want to remove this line from config/app.php:

    'aliases' => [
        'Foo' => \App\Facades\Foo::class,
        // ...
    ]
    

    When my implementation looks like this:

    use App\Facades\Foo;
    
    class Something {
        public function foo() {
            // If Foo is not registered as an alias in `config/app.php`
            // then none of its methods will be auto-completed.
            // Registering it fixes it, obviously.
            return Foo::bar();
        }
    }
    

    Hope this makes sense and I'm not missing anything obvious in the docs, thanks!

    question 
    opened by benjivm 1
  • Type-Error: Illegal offset type in isset or empty

    Type-Error: Illegal offset type in isset or empty

    Versions:

    • ide-helper Version: 2.12.3
    • Laravel Version: 9.42.2
    • PHP Version: 8.1.13

    Description:

    I updated my laravel version from 8 to 9. Since the update I always get the following error when I run: php artisan ide-helper:generate

    ` TypeError

    Illegal offset type in isset or empty

    at vendor/laravel/framework/src/Illuminate/Support/Facades/Facade.php:216 212▕ * @return mixed 213▕ */ 214▕ protected static function resolveFacadeInstance($name) 215▕ { ➜ 216▕ if (isset(static::$resolvedInstance[$name])) { 217▕ return static::$resolvedInstance[$name]; 218▕ } 219▕ 220▕ if (static::$app) {

      +20 vendor frames 
    

    21 artisan:37 Illuminate\Foundation\Console\Kernel::handle(Object(Symfony\Component\Console\Input\ArgvInput), Object(Symfony\Component\Console\Output\ConsoleOutput)) `

    I already reinstalled everything with composer and also cleared the composer-cache. I also ran the command php artisan clear-compiled, but sadly it made no difference.

    Since the error comes from the laravel-framework itself I guess this is a bug in the library?

    Any help would be greatly appreciated :)

    Best Regards, Del

    bug 
    opened by DelDaGhost 0
  • Proposal: Set IDE Helper definitions using PHP 8 Attributes

    Proposal: Set IDE Helper definitions using PHP 8 Attributes

    Set IDE Helper properties using PHP 8 Attributes

    Hi! 👋 There are several recent issues and PRs about the lack of support for Laravel's protected Attribute return-type methods (see #1378 and #1339 for two examples).

    I needed support for this in my app, but went about it in a slightly different way: by using PHP 8 Attributes to tell IDE Helper how to describe methods and properties. (...not to be confused with Laravel's Attributes!)

    I haven't seen any other discussions about this approach. Assuming I've not missed anything, this feels like it could be a better or more flexible way to give developers more control over what IDE Helper produces.

    The code below is specific to my implementation, but if any of the maintainers feel this could be expanded upon and included natively, I'll be happy to put a PR together. Or feel free to borrow the code for your own project 😄


    1. The LaravelAttribute class

    I created a custom PHP Attribute called LaravelAttribute, to annotate protected methods which set class properties that IDE Helper should recognise. It has sensible defaults set, but developers can customise how IDE Helper sets the property if they need to.

    <?php
    
    namespace App\Models\Hooks;
    
    use Attribute;
    use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
    use Illuminate\Support\Str;
    
    /** This attribute specifies the expected return type for a Laravel Attribute accessor. */
    #[Attribute(Attribute::TARGET_METHOD)]
    class LaravelAttribute
    {
        public function __construct(
            public string|array|null $returnTypes,
            public bool $get = true,
            public bool $set = true,
            public bool $nullable = true,
            public ?string $comment = null,
        ) {
        }
    
        /** Automatically apply the Attribute's properties to an IDE Helper docblock. */
        public function apply(ModelsCommand $command, string $methodName): void
        {
            $command->setProperty(
                Str::of($methodName)->snake()->toString(),
                collect($this->returnTypes)
                    ->transform(function(string $type) {
                        $baseClass = Str::of($type)->before('<')->toString();
                        return (class_exists($baseClass) || interface_exists($baseClass))
                        && (! Str::startsWith($baseClass, '\\')) ? ('\\' . $type) : $type;
                    })->join('|') ?: 'mixed',
                $this->get,
                $this->set,
                $this->comment,
                $this->nullable,
            );
        }
    }
    

    2. The ModelHooks class

    IDE Helper supports hooks, so I created a new hook class. It collects all protected methods in each Model class, and checks if they have the LaravelAttribute attribute. If so, it passes the ModelsCommand instance to the apply() method of LaravelAttribute.

    <?php
    
    namespace App\Models\Hooks;
    
    use Barryvdh\LaravelIdeHelper\Console\ModelsCommand;
    use Illuminate\Database\Eloquent\Model;
    use ReflectionAttribute;
    use ReflectionClass;
    use ReflectionMethod;
    
    class ModelHooks implements \Barryvdh\LaravelIdeHelper\Contracts\ModelHookInterface
    {
        /** Use reflection to find LaravelAttributes on class methods, then apply properties with IDE Helper. */
        public function run(ModelsCommand $command, Model $model): void
        {
            collect(
                (new ReflectionClass($model::class))->getMethods(ReflectionMethod::IS_PROTECTED)
            )->mapWithKeys(fn(ReflectionMethod $method) => [
                $method->getName() => collect($method->getAttributes(
                    LaravelAttribute::class,
                    ReflectionAttribute::IS_INSTANCEOF
                ))->transform(fn(ReflectionAttribute $attribute) => $attribute->newInstance())->first(),
            ])->filter()->each(
                fn(LaravelAttribute $attribute, string $method) => $attribute->apply($command, $method)
            );
        }
    }
    

    Then registered it in the config/ide-helper.php file:

    // config/ide-helper.php:
    'model_hooks' => [
        \App\Models\Hooks\ModelHooks::class
    ],
    

    3. Applying LaravelAttribute to Model methods

    With the above in place, I can now add LaravelAttribute to any protected methods in my models. Here's an example for a User. You can specify multiple return types too, and it'll concatenate them (e.g. ['string', 'int'] is treated as a string|int union return type):

    
    // app/Models/User.php:
    
    /** Get the User's full name. */
    #[LaravelAttribute('string', set: false, nullable: false)]
    protected function name(): Attribute
    {
        return Attribute::make(
            get: fn($value, $attributes) => $attributes['first_name'] . ' ' . $attributes['last_name'],
        );
    }
    
    /** Get or update an Address for the User. */
    #[LaravelAttribute(Address::class)]
    protected function address(): Attribute
    {
        return Attribute::make(
            get: fn($value, $attributes) => new Address($attributes['line_1'], $attributes['city']),
            set: fn(Address $value) => [
                'line_1' => $value->line_1,
                'city'   => $value->city,
            ],
        );
    }
    
    /** Map the User's settings to a Collection. */
    #[LaravelAttribute([Collection::class . '<string, bool>'], set: false)]
    protected function settings(): Attribute
    {
        return Attribute::make(
            get: fn($value, $attributes) => collect([
                'dark_mode'   => $attributes['dark_mode'],
                'timezone'    => $attributes['timezone'],
                '2fa_enabled' => $attributes['2fa_enabled'],
            ])
        )->shouldCache();
    }
    
    

    When IDE Helper runs, it will automatically apply properties based on the LaravelAttribute annotations. None of these were previously recognised by IDE Helper, but have now been added to the docblock:

    /**
     * App\Auth\User
     *
     * ...
     * @property-read string $name
     * @property \App\Auth\Address|null $address
     * @property-read \Illuminate\Support\Collection<string, bool>|null $settings
     * ... 
     */
    class User extends Authenticatable {
        // ...
    
    enhancement 
    opened by JackWH 0
  • @mixin Builder instead of @mixin Eloquent?

    @mixin Builder instead of @mixin Eloquent?

    I'm on Laravel 9 but still getting @mixin Eloquent instead of @mixin Builder from ide-helper after "artisan ide-helper:models", which doesn't work for static methods like ::where() on my models. Any idea how tell ide-helper to do that? Or another way to achieve that? Thanks! :)

    opened by drakanor 1
Releases(v2.12.3)
Owner
Barry vd. Heuvel
Barry vd. Heuvel
[Package] Lumen Testing Helper for Packages Development

anik/testbench-lumen is a package, highly inspired by the orchestral/testbench. orchestral/testbench that is a tool for testing Laravel packages.

Syed Sirajul Islam Anik 7 Jun 21, 2022
InfyOm Laravel Generator - API, Scaffold, Tests, CRUD Laravel Generator

InfyOm Laravel Generator Generate Admin Panels CRUDs and APIs in Minutes with tons of other features and customizations with 3 different themes. Read

InfyOmLabs (InfyOm Technologies) 3.5k Jan 1, 2023
:rocket: A Smart CRUD Generator For Laravel

Features Generate your models, views, controllers, routes and migrations just in a few clicks. Models visualization through a graph presentation (New

Houssain Amrani 891 Dec 23, 2022
This package extends the core file generators that are included with Laravel 5

Extended Migration Generators for Laravel 6, 7 and 8 Easily define the migration schema right in your make:migration command. The new commands this pa

Laracasts 2.4k Dec 29, 2022
⛔️ Laravel Tinx is archived and no longer maintained.

⛔️ Laravel Tinx (Deprecated) Laravel Tinx was archived on 12th December 2019 and is no longer maintained. Looking for a reloadable version of Laravel

James Furey 440 Dec 27, 2022
Laravel API Documentation Generator

Laravel API Documentation Generator Automatically generate your API documentation from your existing Laravel/Lumen/Dingo routes. php artisan apidoc:ge

Marcel Pociot 3.3k Dec 21, 2022
A cli tool for creating Laravel packages

Laravel Packager This package provides you with a simple tool to set up a new package and it will let you focus on the development of the package inst

JeroenG 1.3k Dec 22, 2022
A MySQL Workbench plugin which exports a Model to Laravel 5 Migrations

MySQL Workbench Export Laravel 5 Migrations Plugin A MySQL Workbench plugin that allows for exporting a model to Laravel 5 migrations that follow PSR-

Brandon Eckenrode 902 Jan 2, 2023
⚙️ A Laravel package to decompose your installed packages, their dependencies, your app & server environment

Introduction Laravel Decomposer decomposes and lists all the installed packages and their dependencies along with the Laravel & the Server environment

LUBUS 513 Dec 30, 2022
🍪 Write gorgeous documentation for your products using Markdown inside your Laravel app.

LaRecipe Write gorgeous documentations for your products using Markdown inside your Laravel app. LaRecipe ?? LaRecipe is simply a code-driven package

Saleem Hadad 2.1k Dec 29, 2022
Prequel for Laravel. Clear and concise database management.

TL;DR? Test Prequel here! What is Prequel exactly? Prequel is meant to be a database management tool for Laravel to replace the need for separate stan

Protoqol 1.4k Dec 27, 2022
Module Generator Composer Package For Laravel

Module Generator Installation You can install the package via composer: composer require teacoders/module-generator Run the command below to publish t

Tea Coders 21 Jan 8, 2022
Creates an 'artisan workflow:make' command to scaffold out a number of useful GitHub actions workflows for Laravel

Laravel workflow generator This creates a make:workflow artisan command to scaffold out a number of useful GitHub actions workflows for Laravel. Insta

Len Woodward 9 Jul 18, 2021
Laravel IDE Helper

Laravel IDE Helper Generator Complete PHPDocs, directly from the source This package generates helper files that enable your IDE to provide accurate a

Barry vd. Heuvel 12.8k Dec 28, 2022
Open Swoole IDE Helper

Open Swoole IDE Helper This repo works with Open Swoole since release version v4.7.1. This package contains IDE help files for OpenSwoole. You may use

Open Swoole 35 Dec 13, 2022
Magento 2 Debug Helper Module for easy debugging with Xdebug and PHPStorm or any other IDE

Magento 2 Debug Helper Information and Usage Magento 2 Debug Helper Module usage with PHPStorm and Xdebug Installation To install the Magento 2 Debug

Dmitry Shkoliar 13 May 24, 2022
A helper package to flash a bootstrap alert to the browser via a Facade or a helper function.

Alert Box (Laravel) A helper package to flash a bootstrap alert to the browser via a Facade or a helper function. <div class="alert alert-info fade in

Ben-Piet O'Callaghan 17 Dec 30, 2022
Cache-purge-helper - Additional instances where nginx-helper and lscache plugin should be purged.

cache-purge-helper Additional instances where nginx-helper and lscache plugin should be purged. Install Extract the zip file. Upload them to /wp-conte

Jordan 10 Oct 5, 2022
Web Based, Cloud IDE

Codiad Web IDE Codiad is a web-based IDE framework with a small footprint and minimal requirements. Codiad was built with simplicity in mind, allowing

Codiad IDE 2.8k Dec 30, 2022
Make development easier with IDE helpers for Winter CMS!

IDE Helpers This plugin adds barryvdh/ide-helpers package to October for better IDE support. Installation git clone into /plugins/flynsarmy/idehelper

null 4 Dec 11, 2021