Laravel ide helper phpstorm установка

Обновлено: 07.07.2024

Laravel IDE Helper Generator

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.

Require this package with composer using the following command:

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.

If you want to manually load it only in non-production environments, instead you can add this to your AppServiceProvider with the register() method:

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

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

Automatic PHPDoc generation for Laravel Facades

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

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:

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

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.

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.

With the --write-mixin (-M) option

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

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

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

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

Or can be ignored by setting the ignored_models config

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:

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:

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:

The run method will be called during generation for every model and receives the current running ModelsCommand and the current Model , e.g.:

Automatic PHPDocs generation for Laravel Fluent methods

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

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

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.

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.

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.

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:

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.

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 .

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:

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.

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

Laravel - это замечательный фреймворк, который имеет широкий функционал, и много реализаций, облегчающих жизнь программисту. Однако, обратной стороной этого удобства является сложность в чтении кода для IDE. В результате чего, IDE не может проанализировать код должным образом, и построить полное автодополнение кода. Потому, для того, чтобы было удобно работать с Laravel в PHPStorm-е, его необходимо дополнительно настроить.

В этой статье будет рассмотрено:

Предварительная настройка IDE

В каждом новом проекте, который я начинаю в PHPStorm-е, начальные шаги одинаковые: выбор интерпретатора PHP, указание пути к composer-у, NodeJs и JavaScript

Выбор версии PHP и настройка пути к интерпретатору

Настройка версии PHP и интерпретатора находится на вкладке File | Settings | Languages & Frameworks | PHP

В открывшемся окне, будет доступно 2 изменяемые графы:
PHP Language Level - это версия PHP, по которой IDE будет проверять синтаксис вами написанного кода. И в случае несоответствия синтаксису выбранной версии, прямо в IDE вам будет подсвечена ошибка.
CLI interpriter - это путь к интерпретатору PHP.
Если вы ранее не добавляли интерпретаторы, то вам ничего не будет доступно, потому, сейчас его нужно добавить, нажав, справа от выбора интерпретатора, кнопку поиска (2)

После нажатия по (2) кнопке, то появится меню:

Нажав на (1) кнопку, будет предложено на выбор 2 варианта:
From Docker, Vagrant, VM, Remote - в случае, если вы хотите указать удалённый интерпретатор (Docker, Vagrant)
Local Path to Interpreter - чтобы указать локальную версию (как в моём случае)

А в PHP executable нужно прописать путь к php.
Я пользуюсь Laragon, потому мой путь выглядит PATH_TO_LARAGON\bin\php. \php.exe ,

В случае OpenServer, путь будет выглядеть примерно: PATH_TO_OS\modules\php\. \php.exe

Указание путь к composer

Путь к composer-у указывается на вкладке File | Settings | Languages & Frameworks | PHP | Composer

composer

В этом меню нужно переключить опцию в composer.phar, и в этой графе (1) указать путь к исполняемому файлу composer.

И выберите итерпретатор, созданный шагом ранее

У меня, путь к composer-у выглядит так: E:\laragon\bin\composer\composer.phar

NodeJs

NodeJs, его пакетный менеджер, NPM, будет хорошим помощником в подключении всех фронтенд-библиотек. Потому, во-первых, нужно указать путь к самому NodeJs, а во вторых, нужно настроить всё так, чтобы синтаксис Vue-шаблонов был понятен для самой IDE.

node

В меню File | Settings | Languages & Frameworks | Node.js and NPM, аналогично предыдущим пунктам, нужно указать путь к nodeJs (после его указания, автоматически должен подключиться NPM)

JavaScript

JS

Ввиду того, что Vue использует новые ES6 синтаксис для написания шаблонов, то необходимо в самой IDE переключить на поддержку этого синтаксиса на вкладке File | Settings | Languages & Frameworks | JavaScript, выбрав ECMSScript 6

Настройка Laravel

Теперь, осталось провести некоторые настройки, относящиеся к Laravel.

Установка Laravel плагина

laravel-pugin

Теперь нужно установить Laravel-плагин в PHPStorm. Плагины устанавливаются на вкладке File | Settings | Plugins.
Для поиска плагина, в строку поиска нужно вписать laravel

И выбрать интересующий нас Laravel Plugin, который добавляет автодополнение в маршрутах, видах, конфигах.

laravel-pugin-enable

Когда он будет установлен, появится новая вкладка File | Settings | Languages & Frameworks | PHP | Laravel

На которой, нужно поставить галочку на Enable plugin for this project

Настройка VueJs

vue

Для VueJs, аналогично Laravel, так же существует свой отдельный плагин. Чтобы его установить, нужной на вкладке File | Settings | Plugins найти Vue и установить

Подключение нужных библиотек, последние шаги настройки

Сейчас мы уже имеем проект, с которым можно работать. Однако, по-прежнему, нету автокомплита методов в маршрутах, миграциях, Eloquent, ввиду особенной структуры фреймворка. Для решения этой проблемы, нужно скачать библиотеку laravel ide-helper, которая сгенерирует дополнительные мета-файлы для IDE.

Установка IDE-helper

composer-ide-helper

Для установки IDE-helper-а, воспользуемся composer-ом (Tools > Composer > Manage Dependencies)
И в строку поиска, введём: barryvdh/laravel-ide-helper

Установив эту библиотеку, нужно добавить в файл config/app.php, в массив providers: Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class

На этом этапе, уже можно запустить ide-helper, и получить желаемый эффект автокомплита. Но, сделав так в данный момент, эта библиотека возьмёт дефолтные настройки, в которых отключена генерация Fluent-методов. Потому, прежде, скопируем конфиг ide-helper.php с папки vendor/barryvdh/laravel-ide-helper/config, в локальную папку config.
И уже в локальном файле, нужно изменить значение include_fluent на true .

ide-helper-result

Теперь достаточно выполнить команду artisan ide-helper:generate
После чего, появится новый файл _ide_helper.php , который PHPStorm успешно проанализирует, и мы получим желаемое автодополнение:

Автодополнение команд artisan

Сложно заполнить все команды artisan, а постоянно отвлекаться на поиск команд не продуктивно. Благо, в PHPStorm предусмотрена возможность созданий автодополнения команд (File | Settings | Tools | Command Line Tool Support).
Artisan - это команда, основана на консоле symfony, зная это, добавим команду:

Откроется меню, в котором нужно указать:
alias - с какого имени начинаются команды (можно указать a , и вызывать a make:controller .
Path to PHP executable - наш ранее добавленный интерпретатору
Path To Script - путь к artisan-файлу проекта

В результате, должны получить информацию о том, что команды добавлены:

И сейчас, если открыть консоль: Tools > Run Commands

И все команды, которые начинаем с artisan будут подсвечены возможным дополнением

Резюме

Итого, в этой статье была рассмотрена настройка laravel в phpstorm, установка плагинов, так же было показано, как работать с Laravel IDE-helper, настраивать composer и включать автодополнение phpstorm artisan команд

А ещё, рекомендую просмотреть статью, в которой я показываю процесс установки и настройки крутой темы оформления Monokai для PHPStorm, которая тебе точно придётся по вкусе, дорогой разработчик.

Laravel is a free, open source PHP web application framework. It is built on top of several Symfony components, and makes common tasks such as authentication, routing, sessions and caching much easier to implement.

Before you start working with Laravel, make sure that either of the following plugins are installed and enabled:

Additionally, make sure Composer is installed on your machine and initialized in the current project as described in Composer dependency manager.

Watch this video to get a quick overview on Laravel support in PhpStorm:

Install Laravel IDE helper generator

Install Laravel IDE helper generator with Composer. To do this, add a dependency for the barryvdh/laravel-ide-helper package to composer.json . Refer to Install dependencies for details.

Add Laravel IDE helper as a ServiceProvider into the application. In the config/app.php file, add Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class under the providers element:

return array( // . 'providers' => array( // . // Laravel IDE helper 'Barryvdh\LaravelIdeHelper\IdeHelperServiceProvider::class', ), // . );

The Laravel IDE Helper may have to be run after changing or adding services, controllers, models and views. Alternatively, set up File Watchers in PhpStorm to automatically regenerate this file when, for example, composer.json is updated.

You can also install the Laravel generators Composer package to add various Laravel generators for models, views, controllers, and much more.

Coding assistance

The Laravel plugin provides code completion and navigation for various Laravel components: controllers, routes, views, configuration, services, and translations. You can also use Laravel-specific live templates for generating various Laravel entities.

This section describes coding assistance provided by the Laravel plugin. For details on working with the Laravel Idea plugin, see the official documentation.

Code completion

In the editor, press Ctrl+Space to invoke code completion and do any of the following:

Reference a controller when using the Redirect and Route facade's various functions:

Reference a Blade template (or view) when using the View facade:

Reference various keys that are defined in our application's settings when using the Configuration facade:

Complete various translation keys when using the Lang and calling Lang::get() :

Code navigation

To navigate to the declaration of an item, position the caret at its usage and press Ctrl+B . Alternatively, Ctrl+Click the usage.

Navigate to the controller's declaration:

Navigate to a Blade template (or view) declaration:

Navigate to the declaration of a configuration entry or a service:

Navigate to the declaration of a translation key:

Generate code with Live Templates

PhpStorm provides numerous code generation facilities. After downloading and installing the PhpStorm Laravel Live Templates, you can extend the standard live templates set with Laravel-specific live templates, such as:

Input and Request snippets

Route snippets and generation

View, Response and Redirect templates

Building schema (includes column types)

Form and session snippets

Snippets calling various helpers

Blade templates support

Before you start, make sure the Blade plugin is installed and enabled. The Blade plugin is bundled with PhpStorm and activated by default. If the plugin is disabled, enable it on the Installed tab of the Settings/Preferences | Plugins page, as described in Managing plugins.

PhpStorm provides full support of the Laravel Blade template engine. It highlights various Blade syntax constructs, as well as any HTML, JavaScript and CSS code inside the templates.

Besides syntax highlighting, PhpStorm provides several other Blade-specific features.

Code completion for braces and directives

PhpStorm's editor provides code completion both for standard and custom Blade directives, which can be defined In the Settings/Preferences dialog Ctrl+Alt+S under PHP | Blade .

Laravel Blade directive completion

When @for or @foreach directives are used, variable introduction with code completion is available inside the construct's body.

Laravel Blade variable introduction completion

Sections support

While working on a Blade template, you can open a section using the @section directive. PhpStorm provides code completion Ctrl+Space for all known sections' names in the project.

Laravel Blade section completion

PhpStorm provides the code inspection that detects the sections that are not closed using the @stop directive.

Laravel Blade closed section inspection

To navigate to the declaration of a section, position the caret at its usage and press Ctrl+B . Alternatively, Ctrl+Click the usage.

The Laravel plugin also adds a marker to the editor gutter, which lets you navigate to the parent section.

Navigate to the parent section via the gutter icon

Code completion and navigation for extends and includes

Blade templates are often composed of various includes of small reusable blocks, which are in turn other templates. You can also extend templates and provide content for additional sections. PhpStorm and the Laravel plugin provide completion for template names in both the @extends and the @include directives. Completion suggestions include template directory names as well as full template names.

To navigate to the declaration of a template, position the caret at its usage and press Ctrl+B . Alternatively, Ctrl+Click the usage.

Use Alt+F7 to quickly find all template usages in the project.

Language injection in Blade templates

When working with Blade templates, you can inject code fragments inside the template blocks. PhpStorm will provide you with comprehensive language assistance for editing that code fragment.

Inject JavaScript or CSS into a Blade template section automatically

PhpStorm can automatically inject code into Blade template sections based on the defined injection rules. Out of the box, the rules for automatically injecting JavaScript and CSS code are available.

In a Blade template, add a section named javascript (to inject JavaScript) or css (to inject CSS) as follows:

@section('javascript') // injected JavaScript code @stop @section('css') // injected CSS code @stop

PhpStorm will automatically inject JavaScript or CSS into the template sections.

Debug Blade templates

You can debug Blade templates using the same techniques as for regular PHP files.

Debugging Blade templates is supported for Laravel 5.8 or later.

Enable Blade debugging

In the Settings/Preferences dialog Ctrl+Alt+S , go to PHP | Debug | Templates and expand the Blade Debug area.

In the Cache path field, provide the absolute path to the Blade compiled templates cache folder. Type the path manually or click and select the relevant folder in the dialog that opens. By default, compiled Blade templates are stored in the storage/framework/views/ folder inside your project.

Start a debugging session

Start a debugging session as described in the Ultimate debugging guide. The easiest and recommended approach is to use Zero-configuration debugging:

Choose and install the browser extension suitable for your browser.

On the PhpStorm toolbar, toggle to start listening for incoming PHP debug connections, or choose Run | Start Listening for PHP Debug Connections from the main menu.

Set a breakpoint in your code.

Start the debugging session in the browser using the installed browser extension.

During a debugging session, examine the program state: see variable values, evaluate expressions, step through the program, and so on.

See Zero-configuration debugging for the detailed step-by-step instructions, and Advanced debugging scenarios for more debugging scenarios.

Configure Blade templates

Add, modify, or remove Blade directives

Blade directives are managed on the Directives tab of the Blade Page. The tab lists all the currently available Blade directives, for those that have parameters, the prefixes and suffixes are also shown. When you start, the list contains only predefined directives. You can edit these directives as well as create custom ones.

In the Settings/Preferences dialog Ctrl+Alt+S , go to PHP | Blade .

On the Blade page that opens, switch to the Directives tab, which shows a list of all currently available directives.

To define a new directive, click and specify the directive's name in the Name field.

If the new directives requires a prefix and a suffix, select the Has parameter checkbox and type the prefix and suffix to use in the Prefix and Suffix fields respectively. PhpStorm will automatically enclose the prefix and suffix in opening and closing brackets and quotes and add a colon separator : so the parameters will look as follows: ("<prefix>:<suffix>") .

To edit an existing directive, select it in the list and change the values in the fields below.

To restore the original definition, click .

To remove a directive from the list, select it and click .

Configure Blade delimiters

PhpStorm recognizes Blade templates and provides error highlighting and code completion for them based on the delimiters you specify.

In the Settings/Preferences dialog Ctrl+Alt+S , go to PHP | Blade .

On the Blade page that opens, switch to the Text Tags . The fields in the tab show the opening and closing characters for raw tags, content tags, and escaped tags.

The fields are filled in with the default values in compliance with Blade Templates 5.8. If you are using an earlier version, you can specify the relevant custom delimiters and PhpStorm will provide coding assistance according to the new rules.

Use the Artisan command line tool from PhpStorm

PhpStorm integrates with the Artisan command-line interface, which is included with Laravel and provides several handy commands.

Configure Artisan automatically

On project opening, PhpStorm will detect and configure Artisan and display the notification in the Composer Log.

Artisan auto-configuration message in Composer Log

If you want to customize the tool, click to quickly jump to the Command Line Tool Support settings page.

On Windows, automatic Artisan detection requires a configured local PHP interpreter.

Configure Artisan manually

In the Settings/Preferences dialog Ctrl+Alt+S , go to Tools | Command Line Tool Support .

Click on the toolbar.

In the Command Line Tools dialog, choose Laravel from the list, and specify its visibility level ( Project or Global ).

When you click OK , the tool settings dialog opens.

Specify the tool alias, provide the path to artisan , and choose one of the configured PHP interpreters from the PHP Interpreter list. See Configure local PHP interpreters and Configure remote PHP interpreters for details.

Click OK to apply changes and return to the Command Line Tool Support page. Optionally, click to edit the tool properties, or to customize the commands set. See Customize a tool for details.

You can now run the artisan ide-helper:generate command to generate the required PHPDoc information. PhpStorm and the Laravel plugin will use this information to provide code completion and navigation.

Run Artisan commands

From the main menu, choose Tools | Run Command or press Ctrl twice.

In the Run Anything window that opens, type the call of the command in the <artisan> <command> format.

The command execution result is displayed in the Run tool window.

Terminate a command

Click on the Run tool window toolbar.

Debug Artisan commands

Laravel commands are defined in controller classes that extend Command . To debug a command, it is crucial that you initiate a debugging session for the command itself, and not the controller class file it is defined in. Otherwise, the Laravel bootstrapping process will be skipped, and the execution will fail.

In the controller class corresponding to the selected command, click the editor gutter at a code line where you want to set a breakpoint.

Create a run/debug configuration that will run the artisan tool with the selected command. In the main menu, select Run | Edit Configurations , then click and choose PHP Script from the list.

In the PHP Script dialog, provide the run/debug configuration parameters.

In the File field, provide the path to the artisan executable file.

In the Arguments field, type the actual command and its arguments, such as view:cache .

On the PhpStorm toolbar, select the created run/debug configuration and click . The command execution will stop at the specified breakpoint.

Lots of PHP developers create their applications using Laravel, a free, open source PHP web application framework. It is built on top of several Symfony components, and provides a development framework that makes common tasks such as authentication, routing, sessions and caching much easier to implement.

The Laravel IDE Helper

The Laravel Plugin for PhpStorm

Restart the IDE and enable the plugin under Settings (Preferences) | Other Settings | Laravel Plugin | Enable Plugin for this Project. All of a sudden, PhpStorm will know what all Laravel facades do, and provide code completion for controllers, views, routes, configuration, translations and many other things!

Laravel facade - code completion

Laravel navigation features

Working in Blade templates? The Laravel plugin also enhances that experience, for example with code completion for @section directives.

Section directives code completion for Laravel in PhpStorm

Anxious to learn more? Check our Laravel tutorial, which covers getting PhpStorm ready for Laravel development, code completion, navigation, automatic code inspections, command line tool support, debugging and unit testing!

Are you a Laravel developer? Give PhpStorm 8 a try! We have an elaborate tutorial on Laravel support in PhpStorm which will help you get the most out of our IDE. Your feedback is very welcome through the issue tracker, by posting in the comments below, or in our forums!

Читайте также: