Laravel Debug Tip - The beauty of dd()

Posted by Andy Huggins on April 16, 2016

When I first started working with Laravel, I debugged in a slow way. It never occurred to me to make even something so simple as dumping a variable and exiting into an easy (and reusable) function that could be used throughout my project.

Then one day I found `dd()`. One of the simplest function calls, that did everything that I was doing, but when I would do it, it would look like this:


I would type this out over and over, never thinking like "hey, just throw this in a function and make it really short and easy to type, and you'll be ahead of the game." I probably wasted hours typing out var_dump(); exit;

Then along comes Laravel and introduces one of the most basic ideas in programming to me again; The function.

But it doesn't just provide a function for what I was doing, it provides a little more. And this is one of the reasons I am impressed with Laravel as a whole.

Let's take a look at the function and then go over it in further detail, so here it is:

Can be found in Illuminate\Support\helpers.php

So at quick look, it's very simple. But notice some of the details of what is going on here. The first line is a check to see if the function is already defined in the app, this prevents any naming errors, or "Cannot redeclare function" errors.

A very to the point doc bloc, no explanation needed.

The function definition has a little more than what I was using. So what is going on here?

It makes a call to array_map, which is a PHP function that applies the passed callback to the given array. Which in this case, creates a new instance of the Dumper object and calls the dump function on the array_value. But if you notice, the second parameter to array_map, is a call to func_get_args(), which is a PHP function that returns an array of the functions argument list. But in this case it is referring to the dd() function call. This means that you can pass any number of arguments to dd(), as well as dump(), and they will all be output.

This means you can do something like dd('in test function', $test, $example, $another) instead of making a function call for each of the parameters. It just saves you a few characters and can allow you to easily flag a dump, so you can see where the application is exiting.

This function is so simple, actually no, it's not simple, it's elegant. It does a great job with very little code and is super helpful. As I mentioned, I have found myself typing dd() in Javascript.

I look at this as a reminder to give everything a little more thought. When writing code, I always try to ask myself, how can I make this more reusable, how I can make this easier, but let's not forget to make things flexible when we can.