« Back
Written by Nuno Maduro on September 23, 2022

How I've Added The Source File And Line To Laravel's "dd" function

Next week, on Laravel v9.32.0, we are going to improve the dd function output adding the source file/line next to the dumped output.

DD Example

Some people have asked me how is possible to get the source file/line from the dd function call, so in this article, I going to share some details about this pull request: github.com/laravel/framework/pull/44211.

PHP has an insane power function called debug_backtrace. This function tells the chain of events that led up to the call to debug_backtrace.

So, if our dd function originally looked something like this:

function dd($var)
    die(var_dump($var));  // dump the output...

dd('foo'); // string(3) "foo"

We can make use of the debug_backtrace to print the source file/line right before dumping the output:

function dd($var)
    $trace = debug_backtrace();

    $file = $trace[0]['file']; // The original "file" where the `dd` call was made...
    $line = $trace[0]['line']; // The original "line" where the `dd` call was made...

    echo "// $file:$line\n"; // print the source file:line...


// my-app/index.php:14
// string(3) "foo"

And that’s it! Please refer to PHP’s official documentation to learn more about this function.

I hope you have enjoyed this article. If yes, please consider supporting my work — my mission is to spend more time maintaining the dozens of projects that I've written/collaborated on over the years and continue developing new projects to PHP development more productive and enjoyable.