Quickly dd anything from the commandline

Laravel's tinker command allows to run any code you want as if you are inside your Laravel app. But if you want to run a single line of code if can be a bit bothersome. You must start up tinker, type the code, press enter, and quit tinker. Our new spatie/laravel-artisan-dd package contains an Artisan command to dd anything from the commandline. No need to start and quit tinker anymore. Here's a simple example of how you can use it: You can dd anything you want. Of course the output will be pretty printed. Here's an example where an Eloquent model is dumped. Multiple pieces of code can be dumped in one go:
php artisan dd "bcrypt('secret')" "bcrypt('another-secret')"; 
The dd artisan command using PHP's eval to run arbitrary code. Be aware that this can be potentially dangerous. By default the command will only run in a local environment. You can make it run in other environments by setting an ALLOW_DD_COMMAND enviroment variable to true. If you like this package go check it out on GitHub. This isn't the first package our team has made. Go check out this big list of Laravel packages on our company website to learn if we've made anything that could be of use to you.

Setting up Xdebug with Laravel Valet

On most of my day to day work I use Laravel Valet to develop locally. When hitting a bug often I just put a dd() statement in the code to quickly inspect what's going on. But when encountering a complex bug this becomes tedious. Wouldn't it be nice if we could add a breakpoint to our code and be able to inspect the values of all variables in one go (and even execute the script line by line)? Enter Xdebug. In this post I'll show you easy it is to install and use it.

Installing Xdebug

I'm going to assume that you have are running macOS, have latest version of PHP installed together with homebrew. To install xdebug, just run this command:
brew install php71-xdebug
In the last lines of the output of the installation indicated that there's a new ini file created at /usr/local/etc/php/7.1/conf.d/ext-xdebug.ini. By running php --ini you can verify that php is reading that setting file. Go ahead and add these lines to that file:
xdebug.remote_enable=true
xdebug.remote_host=localhost
xdebug.remote_port=9000
xdebug.remote_handler=dbgp
The above settings are needed to allow PHPStorm to connect to Xdebug. You can look up the meaning of the individual settings in the xdebug documentation. Port 9000 seems to be the default, but you may choose another port if you like.

Debugging a cli command

If you want to follow along with the rest of this post, create a fresh copy of laravel in a directory you parked with Valet. In my mac I've parked the /Users/freek/dev/sites directory. In that directory I ran laravel new laravel to create fresh copy of Laravel in the laravel directory. Let's first test out if we can add a breakpoint to a script that is running on the command line. Open up the newly created project in PHPStorm. In the Debug preferences in PHPStorm make sure the debug port is set to the same value you specified in the ini file. Also uncheck "Force break at the first line when a script is outside the project". Next up, select "Start listening for PHP Debug Connections" from the "Run" menu. Let's add our first breakpoint. Open up routes/console.php and add a breakpoint by adding click in the sidebar left on the $this->comment(... line. Now let's run the command in which we just place a breakpoint. Got to the command line and execute php artisan inspire. And boom, xdebug should activate. In the variables pane you can now inspect every single variable in the script. In the console pane you can run arbitrary code. Handy! Explaining the Xdebug UI in PHPStorm is out of scope for this article. Read the PHPStorm docs to know more or just play around with it.

Debugging a web request

In order to trigger Xdebug a special cookie needs to be set on the webrequest. You can use the bookmarklets provided by Jetbrains to set those cookies. Personally I prefer using the Chrome Xdebug Helper extension. With the extension installed just point your browser to your site, click on the little bug icon next to the address bar, and choose "Debug". That bug icon should turn green now indicating that the right cookies have been set. Now go to the a piece of code in your project that should run when the web request is performed. In my case I'm going to set a breakpoint in web/routes.php. When refreshing the webpage you should first see this dialog indicating that PHPStorm got an incoming connection from Xdebug. After clicking "Accept" you should hit your breakpoint. Congratulations on your working Xdebug installation!

A word on performance

With Xdebug enabled your PHP code will run a lot slower. Luckily Djamil Legato coded up an xdebug toggler make it easy to switch xdebug on and off with a single command. You might see this warning when running composer:
You are running composer with xdebug enabled. This has a major impact on runtime performance.
To solve that just update to the latest version of composer which can automatically detect and temporarily turn off Xdebug while it's running.
If you had trouble following this guide, you might take a look at this video by Gary Hockin. He dives a little bit deeper in the Xdebug integration in PHPStorm. Happy debugging!

A better dd() for your TDD

On the Tighten blog Keith Damiani wrote an article how you can mold the dd helper to your liking.
An important part of every Laravel developer's debugging arsenal is the humble dd() helper function—"dump and die"—to output the contents of a variable and terminate execution of your code. In the browser, dd() results in a structured, easy-to-read tree, complete with little arrow buttons that can be clicked to expand or hide children of nested structures. In the terminal, however, it's a different story. ... Fortunately, it's simple to build your very own customized version of dd() to help tame your unwieldly terminal output.
https://blog.tighten.co/a-better-dd-for-your-tdd

Beyond Console Debugging Tricks

Daniel Reis shows some alternatives for the best known form of debugging JavaScript console.log.
I don’t consider myself a nitpicker. That’s only true, and it’s all fine and dandy… until I find a console.log() that someone forgot to remove from the JavaScript code. And if we’re talking about debugger statements… all hell breaks loose! ... I collected some of the most common examples I can present as proper alternatives for that process.
https://medium.com/outsystems-experts/beyond-console-debugging-tricks-f7d0d7f5df4

Debugging collections

Lately I've been working a lot with collections in Laravel. If you're not in the know: a collection is a sort of super charged array with a lot of powerful functions to transform the data inside it. The only thing I found a bit of a hassle is how to debug the various steps in a collection chain. Here's how I improved the workflow. Using a collection class you can build up a chain of functions to transform data. Take a look at this example (I left out the function bodies to make it a bit shorter).
collect($items)
  ->filter(function() { 
     ... 
   })
   ->unique(function() { 
      ... 
   })
   ->map(function() {
     ... 
   })
   ->sortBy(function() { 
      ...
   });
Image you are debugging this code. You want to see what the values are after the map function. To do that you could wrap the code starting from the collection call until right after the map function in a dd function.
dd(collect($items)
  ->filter(function() { 
     ... 
   })
   ->unique(function() { 
      ... 
   })
   ->map(function() {
     ... 
   }))
   ->sortBy(function() { 
      ...
   });
Sure enough, the contents of the collection after the map function will get dumped to the screen. But there's some work involved: you have to insert code a the beginning of the collection and an extra closing parenthesis after the map function. To my eyes this isn't very readable. It's also a bit of a hassle to remove the dd statement, that closing parenthesis is easily forgotten. I'm exaggerating the problems a bit, but I can assure you'll get tired of debugging like this really quick. There must be a better way. Laravel's collection class is Macroable. That means we can add functions to the class at runtime. To improve our debugging workflow let's create a simple dd macro:
Collection::macro('dd', function () {
    dd($this);
});
To use the macro anywhere in a project you could place it a ServiceProvider. Take a look Blender, our Laravel template, for an example. Using the macro debugging a collection becomes much simpler. Here's how to use it:
collect($items)
  ->filter(function() { 
     ... 
   })
   ->unique(function() { 
      ... 
   })
   ->map(function() {
     ... 
   })
   ->dd()
   ->sortBy(function() { 
      ...
   });
To see the values after a particular step in the chain you simply have to add one line of code. It's perfectly readable. After you've done your debugging there's only one line to remove. Using PHPStorm's alt+shift+arrow-up and alt+shift+arrow-down shortcuts the ->dd() line can be easily moved to the previous or next part of the collection chain. You can learn more about collections in Laravel's official documentation and Adam Wathan's excellent book on the subject.