Laravel Phpstorm



  1. Laravel Phpstorm Code Style
  2. Phpstorm Laravel Alias
  3. Laravel Phpstorm

It is well known that Laravel works in magical ways to be a developer-friendly framework and make it super easy for you to bootstrap your ideas to fruition with as little friction as possible. With all that magic, though, comes the difficulty for your code editor to provide meaningful IntelliSense suggestions. Here’s how to fix it.

  1. Browse other questions tagged laravel docker phpstorm or ask your own question. The Overflow Blog Podcast 332: Non-fungible Talking. The Loop: Our Community & Public Platform Roadmap for Q2 2021. Featured on Meta Stack Overflow for Teams is now free for up to 50 users, forever.
  2. Mastering PhpStorm is the course he wishes he had when he started working with this IDE. Laravel News Readers Get a 10% Discount. Could you relate to the mentioned drawbacks of PhpStorm? Do you feel like you can improve your PhpStorm workflows too? You are only one more step away to level up your IDE skills.

If you develop web applications you certainly heard of Laravel, a PHP framework that uses HMVC architectural pattern, currently at version 5.1.4. The best IDE currently available for Laravel is JetBrains PhpStorm, available for Windows, Mac OS X and Linux.

The example project

To illustrate what we're dealing with and progress looks like in solving the IntelliSense issues for Laravel projects, I have created a dummy project to showcase a few simple examples.

This very fictitious and a pretty standard project has the default AppUser model which has a couple of extra relationships:

  • A User has many forum Threads through ->threads() relationship;
  • A Thread belongs to an owner user User through ->owner();
  • a Thread has many Posts by various users through ->posts() relationship.

We also have a SearchService for the sake of illustrating some parts other than just model relationships. Bear with me.

The examples I'll give will be from various ThreadsController methods to illustrate different kinds of missing IntelliSense and how it's solved later on.

The example code editor

For this example I will be using Visual Studio Code. With no support for Laravel out of the box and VS Code being one of the most popular code editors makes it the perfect choice for this article.

What it looks like at the very beginning

On a fresh VS Code install, you'll most likely notice that even the most basic IntelliSense for PHP is missing. It does not even find the related class that's part of the project.

Laravel Phpstorm Code Style

Let's fix that.

PHP Intelephense

Open up your VS Code Extensions tab and search for PHP Intelephense. It's a fast and powerful code IntelliSense provider for your PHP language files. It is by far much faster than other alternatives you'll find on the VS Code Extension marketplace. Go ahead and install it.

Once installed, it's going to start indexing the project (searching for PHP classes, methods, symbols, etc) so it can have a better understanding of the project's structure as well as making it super fast.

Let's look at where it gets us!

We're now getting some help from VS Code! IntelliSense now recognises the existing Thread and ThreadsController classes and bumps them up to the top as the most relevant - in which case, they are! Once I select the first result and press <Enter>, it will automatically import the use AppThread statement at the top as well. Helpful!

There's something missing

Now let's try to use some relationships.

Looking at the code here we know clearly that the $thread->owner relationship returns a User model, but the PHP Intelephense extension can't yet make sense of that. It has no idea that trying to access owner as a property on a Laravel's Model instance will actually fallback to the owner() method on the instance, resolve the actual relationship, fetch the data from the database, and return a new instance of the related model. That's a lot of Laravel's magic in one place.

Let's look at another example. Let's resolve the SearchService class using the Laravel's Service Container:

We can see that the SearchService has two methods: findPosts() and findThreads() - nonewere suggested after resolving the service from the Service Container. How can we fix that?

Laravel IDE Helper

Barryvdh is a legendary contributor to the Laravel community and Open Source in general. You are most likely using at least one of his open source packages already, such as Laravel Debugbar or Laravel CORS.

To help us today with the IntelliSense problems we have been experiencing, we will be installing another one of Barry's legendary packages -Laravel IDE Helper.

First, let's install it via Composer:

Next, we will need to run a few commands to generate a few helper files. These will help by providing more information to IntelliSense for it to understand more of the Laravel's magic. Let's run these commands:

If all went well, you will now have three new files in your project's root:

  • _ide_helper.php
  • .phpstorm.meta.php
  • _ide_helper_models.php

With any luck, PHP Intelephense will look at these files immediately and begin indexing the classes and methods available in your project. Let's see what that gets us.

That's better. Now accessing a relationship as a property returns the appropriate model. What about the Service Container?

Much, much better. IntelliSense recognises the class instance being returned from the app() helper method is now the SearchService and it correctly suggests the available methods on this class.

We have gone from no suggestions at all - to meaningful suggestions. This makes for a much faster and a more enjoyable coding experience while working on a Laravel project using Visual Studio Code. All thanks to the PHP Intelephense extension and the Laravel IDE Helper package!

Cleaning up

It can be a little tedious to constantly re-generate these helpers files in order to keep up with new changes, especially when working in a large team. Let's make it better.

.gitignore

First, let's add these files to your .gitignore so they're not committed to the project's repository. There is no need to have these helper files as part of the repository because it will definitely pollute your Pull Requests will changes to these helper files and nobody likes the extra unrelated code in a PR.

Composer hook

Another way to automatically update the helper files is to call the IDE Helper commands automatically after Composer updates. Just insert this into your 'scripts' array in your composer.json file:

Now whenever you install or update your Composer packages, the helper files be automatically re-generated. Because these files are now also ignored by Git, there is no harm in constantly updating them.

As an added bonus, your colleagues will automatically get these helpers as well and their IDEs will pick up on them to make their development experience better as well! How cool is that :)

I hope this has helped. If you do have issues with the Laravel IDE Helper package, please refer to it's documentation here.

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 the Laravel (free) or Laravel Idea (paid) plugins are installed and enabled. Both plugins additionally require installing the Laravel IDE helper tool.

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

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

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

    return array( // ... 'providers' => array( // ... // Laravel IDE helper 'BarryvdhLaravelIdeHelperIdeHelperServiceProvider::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:

  • Blade directives

  • Input and Request snippets

  • Cookie snippets

  • Route snippets and generation

  • View, Response and Redirect templates

  • Building schema (includes column types)

  • Cache

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

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

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.

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

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.

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

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

  2. In the Cache path field, provide the path to the Blade compiled templates cache folder. Type the path manually or click and select the relevant folder in the dialog that opens.

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:

  1. Choose and install the browser extension suitable for your browser.

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

  3. Set a breakpoint in your code.

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

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

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

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

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

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

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

    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

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

  2. Click on the toolbar.

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

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

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

Laravel

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.

Phpstorm Laravel Alias

Terminate a command

  • Click on the Run tool window toolbar.

Laravel Phpstorm

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.

Laravel Phpstorm

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

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

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

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