Do not speak Portuguese? Translate this site with Google or Bing Translator
Start with Laravel in VS Code on Docker

Posted on: August 08, 2024 05:20 PM

Posted by: Renato

Categories: Docker Laravel

Views: 122

Start with Laravel in VS Code on Docker

by Miloslav Beno
18 minutes
Start with Laravel in VS Code on Docker

Imagine you are part of the team and you want each member to develop in one standardized environment. They can have different operating systems and use different development tools or IDEs, but you want to have one unified environment with all the required dependencies.

Or if being part of the team isn't your thing, you might want a standardized environment for yourself as well. You want to keep the project separate from your local environment. Or when you are done with the project and you leave it for a while, then return to it, you want to be able to start where you finished. Even if it was some time ago and you have a new computer. You want to be able to set everything up, as you had it before, and start to work quickly.

We will use a tool called Laravel Sail - a command-line tool that should simplify the whole process and shield us from the complexities of such a setup.

Requirements

For this tutorial you will need:

Now, I'm going to use Windows in this tutorial, but you should be able to follow with any other OS. There might be just slight differences. Particularly when dealing with some issues that are not going to apply to you.

Getting the Laravel

  • First, in Windows press Win + R and type wsl, hit ENTER

  • Create a directory where are you going to work on the project.

    When I first wrote this tutorial I used /mnt/c/Miloslav/Projects/Recent/laravel_test/example-app but one careful reader (thanks Ken Verhaegen) has point out to me that this is not ideal for performance reasons. It's better to create the directory outside of /mnt/c, e.g. ~ works fine and you can always access it from Windows through network share. In my case \\wsl.localhost\Ubuntu-22.04\home\miloslav

  • Now, when you are in the target directory, run this command

curl -s "https://laravel.build/example-app?with=mysql,redis&devcontainer" | bash 

Since I want to use other components, not just Laravel itself, I'm specifying those in with query parameter. In particular, it's going to be MySql and Redis. The other query argument devcontainer instructs sail to create a default devcontainer.json file for us. Do not worry for now, if you don't know what is that - I will explain later.

Note: In my case, when I first run this command, I got this error output: Docker is not running

What I had to go to Docker desktop settings (You can right click on Docker Desktop icon in systray and select Settings). Under Resources, open WSL integration and check in which WSL distros you want to access Docker from.

WSL Integration

That should do the trick and you will be able to run the command.

  • Let the thing do the work:

Getting the laravel

  • Once finished, go to the new directory cd example-app.

Laravel downloaded

  • Run this command to start a new instance of VS Code opened from the current location:
code .

Note: I hit the wall again when I first run the command and received this message:

Code not found

For some reason code command couldn't be found. When I check the path by running:

echo $PATH

I couldn't find the VS Code there. Simple solution would be to make sure there is path to the VS Code directory - in my case it would be /mnt/c/Users/milko/AppData/Local/Programs/Microsoft VS Code/bin.

But instead of manually adding VS Code to the PATH in WSL, I just installed a new Linux distribution through Microsoft Store (I wanted to do it anyway) - Ubuntu-22.04 and PATH should be updated there.

Then I checked which container is wsl using (In windows Command Line): wsl --list -v

    NAME                   STATE           VERSION
  * Ubuntu                 Running         2
    Ubuntu-22.04           Stopped         2
    docker-desktop         Stopped         2
    docker-desktop-data    Stopped         2

I had to switch the container to the new Ubuntu wsl -s Ubuntu-22.04,

Then I restarted wsl and code . worked now.

Visual Studio Code in WSL

The Visual Studio Code will start in WSL. You will know that when you check the bottom left corner of VS Code window. You should see this green tag:

Opened in Ubuntu icon

VS Code will also immediately want to reopen this folder in Dev Container since it detected devcontainer.json file. It will notify you with this message:

Opened in Ubuntu icon

Don't do that just yet and let's examine the devcontainer.json file first. You will find it in .devcontainer folder.

Customizing devcontainer.json file

The file instructs VS Code which container (or multiple containers) to open and what other customizations should perform. In this case, dockerComposeFile points to the docker-compose.yml generated by the Laravel Sail which specifies particular containers for our services (we wanted Mysql and Redis) and how they are connected. Since Laravel Sail is here to simplify this whole process, we will not worry about the content of docker-compose.yml and just trust that the sail did a good job.

Let's make slight changes to devcontainer.json. We will want to have full PHP support in the container. So we are going to add PHP Tools extension DEVSENSE.phptools-vscode to the extensions section and also specify code style settings php.format.codeStyle for the formatter (one component of the PHP Tools). Laravel uses PSR-2, so that's what we are going to use. You can just copy the whole file from here:

// https://aka.ms/devcontainer.json
{
    "name": "Existing Docker Compose (Extend)",
    "dockerComposeFile": [
        "../docker-compose.yml"
    ],
    "service": "laravel.test",
    "workspaceFolder": "/var/www/html",
    "settings": {
        "php.format.codeStyle": "PSR-2"
    },
    "extensions": [
        "DEVSENSE.phptools-vscode"
        // "mikestead.dotenv",
        // "amiralizadeh9480.laravel-extra-intellisense",
        // "ryannaddy.laravel-artisan",
        // "onecentlin.laravel5-snippets",
        // "onecentlin.laravel-blade"
    ],
    "remoteUser": "sail",
    "postCreateCommand": "chown -R 1000:1000 /var/www/html"
    // "forwardPorts": [],
    // "runServices": [],
    // "shutdownAction": "none",
}

If interested, you can examine the whole specification of devcontainer.json here

Enable Xdebug in the Laravel container

Since we want to be able to debug php code in the container, we will need to turn that on.

Open .env file and append the following lines which will turn on Xdebug step debugging mode and instruct it to try to connect back to the VS Code on each request:

SAIL_XDEBUG_MODE=debug
SAIL_XDEBUG_CONFIG="start_with_request=true"

Note: By default Laravel will be server from port 80. If you have already another web server installed localy which is bound to this port, the container will not start. You would need to either stop the local web server, or add APP_PORT=8080 to .env file. That would change the port from where the Laravel will be served.

Now we are ready to start the containers and launch another VSCode instance directly in the Laravel container.

Launch VS Code in the Container

Start the terminal (Ctrl + ~), if it's not opened already. And run the following:

./vendor/bin/sail up -d

Laravel Sail will create the containers and start them. Normally, this wouldn't be a required step. VS Code itself can compose, build and run containers specified in devcontainer.json, but at the time of writing it didn't pick up the changes I've made to .env file. There is a related issue on Github and I will update the article once resolved - maybe I just need to put something to the devcontainer.json? - If you know, please write me in the comments below.

The other thing we want to do is to get barryvdh/laravel-ide-helper package and instruct it to generate files that will hep the IntelliSense engine to provide accurate auto-completions for Laravel.

First, open up composer.json and update post-update-cmd by adding these commands:

    "scripts": {
        "post-update-cmd": [
            "@php artisan ide-helper:generate",
            "@php artisan ide-helper:models",
            "@php artisan ide-helper:meta"
        ],
    },

They will regenerate ide helper files on each time you update your dependencies. Then run the following command to get the package:

./vendor/bin/sail composer require --dev barryvdh/laravel-ide-helper

Once finished, press F1 and select Reopen in Container.

Reopen in Container

The folder will reopen in the new VS Code window. Now, the new VS Code instance is running in the container with Laravel. At this point, I'm starting to feel like I'm opening Matryoshka dolls - launching VS Code in one container from VS Code in another container.

Debug the Laravel in the Container

First, let's check if we have Laravel up and running and accessible from the local machine. On Windows, open your favorite browser and type localhost. If you have changed the port with APP_PORT, use that port in the URL (e.g. localhost:8080).

Laravel in the browser

Now, to debug open public/index.php, place a breakpoint there and hit F5. Since we do not already have any launch.json file specifying what the launch should do, we will get these default options. Click Listen for Xdebug.

Listen for Xdebug

Then go back to the browser and refresh it. The debugger should break on the line with the breakpoint.

Debugging Laravel in Visual Studio Code

Working with Mysql and Redis

Since we've instructed Sail to install and configure Mysql and Redis too, they are now available in their separate containers, but available to the Laravel container. To test that, open resources/views/welcome.blade.php file, delete the default welcome content in the body and replace it with the following:

<body class="antialiased">
    <h1>Laravel in the Container</h1>
    <p>Visits {{$visits}}</p>
    <p>MySql version {{$mysql_version}}</p>
</body>

Then open routes/web.php and replace it completely with the following:

<?php

use Illuminate\Support\Facades\Redis;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider within a group which
| contains the "web" middleware group. Now create something great!
|
*/

Route::get('/', function () {
    return view('welcome', [
        'visits' => Redis::incr('visits'),
        "mysql_version" => DB::select("select version()")[0]->{'version()'}
    ]);
});

This way we will check if we have both Redis and Mysql ready to go. Just refresh the browser with localhost address.

Laravel in browser with services

Testing

One more thing you can find useful is the unit testing support. In VS Code, click on the tests icon in the left menu bar. You should see the example tests defined in the tests folder. You can run them in bulk by clicking on the play button:

Laravel example tests

Or run and debug them individually by right-clicking on the test and selecting Debug Test.

Debugging Laravel example test

Conclusion

That's it! You have successfully created and configured a standardized development environment for Laravel in Visual Studio Code on Docker. You can debug and test Laravel. And you have Redis and Mysql up and running. I hope your Laravel development needs are covered. But if you find anything else worth mentioning, I will gladly take a look. Please let me know in the comment below. Thank you.

- https://blog.devsense.com/2022/laravel-on-docker - https://github.com/lucenarenato/laravel-on-docker

2

Share

Donate to Site


About Author

Renato

Developer

Add a Comment
Comments 0 Comments

No comments yet! Be the first to comment

Blog Search


Categories

OUTROS (16) Variados (109) PHP (133) Laravel (171) Black Hat (3) front-end (29) linux (114) postgresql (39) Docker (28) rest (5) soap (1) webservice (6) October (1) CMS (2) node (7) backend (13) ubuntu (56) devops (25) nodejs (5) npm (3) nvm (1) git (8) firefox (1) react (7) reactnative (5) collections (1) javascript (7) reactjs (8) yarn (0) adb (1) Solid (2) blade (3) models (1) controllers (0) log (1) html (2) hardware (3) aws (14) Transcribe (2) transcription (1) google (4) ibm (1) nuance (1) PHP Swoole (5) mysql (31) macox (4) flutter (1) symfony (1) cor (1) colors (2) homeOffice (2) jobs (3) imagick (2) ec2 (1) sw (1) websocket (2) markdown (1) ckeditor (1) tecnologia (14) faceapp (1) eloquent (14) query (4) sql (40) ddd (3) nginx (9) apache (4) certbot (1) lets-encrypt (3) debian (12) liquid (1) magento (2) ruby (1) LETSENCRYPT (1) Fibonacci (1) wine (1) transaction (1) pendrive (1) boot (1) usb (1) prf (1) policia (2) federal (1) lucena (1) mongodb (4) paypal (1) payment (1) zend (1) vim (4) ciencia (6) js (1) nosql (1) java (1) JasperReports (1) phpjasper (1) covid19 (1) saude (1) athena (1) cinnamon (1) phpunit (2) binaural (1) mysqli (3) database (42) windows (6) vala (1) json (2) oracle (1) mariadb (4) dev (12) webdev (24) s3 (4) storage (1) kitematic (1) gnome (2) web (2) intel (3) piada (1) cron (2) dba (18) lumen (1) ffmpeg (2) android (2) aplicativo (1) fedora (2) shell (4) bash (3) script (3) lider (1) htm (1) csv (1) dropbox (1) db (3) combustivel (2) haru (1) presenter (1) gasolina (1) MeioAmbiente (1) Grunt (1) biologia (1) programming (22) performance (3) brain (1) smartphones (1) telefonia (1) privacidade (1) opensource (3) microg (1) iode (1) ssh (3) zsh (2) terminal (3) dracula (1) spaceship (1) mac (2) idiomas (1) laptop (2) developer (37) api (5) data (1) matematica (1) seguranca (2) 100DaysOfCode (9) hotfix (1) documentation (1) laravelphp (10) RabbitMQ (3) Elasticsearch (1) redis (2) Raspberry (4) Padrao de design (4) JQuery (1) angularjs (4) Dicas (43) Kubernetes (3) vscode (2) backup (1) angular (3) servers (2) pipelines (1) AppSec (1) DevSecOps (4) rust (1) RustLang (1) Mozilla (1) algoritimo (1) sqlite (1) Passport (2) jwt (5) security (2) translate (1) kube (2) iot (1) politica (2) bolsonaro (1) flow (1) podcast (1) Brasil (1) containers (3) traefik (1) networking (1) host (1) POO (2) microservices (2) bug (1) cqrs (1) arquitetura (3) Architecture (4) sail (3) militar (1) artigo (1) economia (1) forcas armadas (1) ffaa (1) autenticacao (2) autorizacao (2) authentication (4) authorization (3) NoCookies (1) wsl (4) memcached (1) macos (2) unix (2) kali-linux (1) linux-tools (5) apple (1) noticias (2) composer (1) rancher (1) k8s (1) escopos (1) orm (1) jenkins (4) github (5) gitlab (3) queue (1) Passwordless (1) sonarqube (1) phpswoole (1) laraveloctane (1) Swoole (1) Swoole (1) octane (1) Structurizr (1) Diagramas (1) c4 (1) c4-models (1) compactar (1) compression (1) messaging (1) restfull (1) eventdrive (1) services (1) http (1) Monolith (1) microservice (1) historia (1) educacao (1) cavalotroia (1) OOD (0) odd (1) chatgpt (1) openai (3) vicuna (1) llama (1) gpt (1) transformers (1) pytorch (1) tensorflow (1) akitando (1) ia (1) nvidia (1) agi (1) guard (1) multiple_authen (2) rpi (1) auth (1) auth (1) livros (2) ElonMusk (2) Oh My Zsh (1) Manjaro (1) BigLinux (2) ArchLinux (1) Migration (1) Error (1) Monitor (1) Filament (1) LaravelFilament (1) replication (1) phpfpm (1) cache (1) vpn (1) l2tp (1) zorin-os (1) optimization (1) scheduling (1) monitoring (2) linkedin (1) community (1) inteligencia-artificial (2) wsl2 (1) maps (1) API_KEY_GOOGLE_MAPS (1) repmgr (1) altadisponibilidade (1) banco (1) modelagemdedados (1) inteligenciadedados (4) governancadedados (1) bancodedados (2) Observability (1) picpay (1) ecommerce (1) Curisidades (1) Samurai (1) KubeCon (1) GitOps (1) Axios (1) Fetch (1) Deepin (1) vue (4) nuxt (1) PKCE (1) Oauth2 (2) webhook (1) TypeScript (1) tailwind (1) gource (2)

New Articles



Get Latest Updates by Email