How To DD With Headers In Laravel

Last updated 11th November, 2023

Introduction

dd and dump are two of the most useful tools in your Laravel debugging toolkit. If you're developing an API, and a client to consume that API, you might encounter a CORS error when attempting to dump using Laravel's helpers.

There are a couple of main reasons this can happen:

  • The response type of the request doesn't match the expected response type, because dd and dump are changing it.
  • Your CORS middlware that adds access control headers isn't being triggered before the dd function ends the request.

The Workaround Code

What you can do is set your own headers when you're dumping. This should allow the client to accept the response and display your dumped debug logs.

// Pass the function a variable number of arguments,
// just like the original dd and dump method...
function ddh(mixed ...$vars) {
    // Now we can set our access control policy to
    // accept all...
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: *');
    header('Access-Control-Allow-Headers: *');

    // Finally call the original dd method...
    dd(...func_get_args());
}

Is This Safe To Use?

This is a bit of a hack. Usually this would be a really bad idea, and could create serious insecurity. However, because we're in a development context, and we shouldn't have any dump or dd references left in production, this is generally ok as a workaround.

You can also define a similar function for dump:

function dumph(mixed ...$vars) {
    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: *');
    header('Access-Control-Allow-Headers: *');
    
    dump(...func_get_args());
}

Hope this helps 🤙

No comments yet…

DevInTheWild.

Login To Add Comments.

Want More Like This?

Subscribe to occasional updates.

Related Articles