How to debug Laravel apps

Debugging is part of every developer’s life. The better you are at solving problems, the more efficient you will be. While the basics of debugging are the same for any programming language, you can always use specific tools and get to know best practices.

We’ll round up everything you need to know about debugging with Laravel in this article, including some personal recommendations from our toolkit!

Debugging Basics

What kind of bugs are common in Laravel apps?

If you’re building an app or API, there are many parts where things can go wrong. Here are some common problems:

  • Syntax errors like missing semicolons, unclosed quotes, misplaced or missing brackets, extra commas or undefined variables
  • Routing issues like incorrect or missing routes and/or parameters
  • Database errors like SQL query errors or incorrect column types in your database
  • Controller/Model errors like calling undefined methods or forgetting to import controllers/models
  • Environment configuration issues like failing database connections caused by errors in your .env file
  • Session or cache issues like timeouts that log out your users unexpectedly or mistakes in storing and retrieving data
  • CORS (Cross-Origin Resource Sharing) errors while building APIs, caused by wrong configuration
  • Authentication problems that arise from incorrectly defined policies and checks
  • Dependency / Composer issues resulting in a class being not found, often because of an issue with Composer’s autoloading
  • … and ♾️ more

Debugging process

To find and fix these problems, you will need to go through a few structured steps instead of randomly trying to change your code.

  • If you can reproduce the bug you will know what exact action is problematic.
  • Ask yourself what is the expected behaviour, and notice what is happening instead.
  • Then it’s time to identify the root cause of your bug. This is usually the hardest part - that’s why we have many tools to help us with that step. (Check the next chapter!)
  • If you have found the problem, you should now be able to fix your code. Surprisingly, this is usually easy compared to finding the cause!
  • Afterwards, verify if your code is now working as intended, deploy your fix and call it a day. Success!

Laravel Debugging Tools

Finding the root cause of a bug is always the most tricky part of debugging, because there are many possible points of failure. We need to start looking for hints like variables with the wrong value, or functions that should have been called but weren’t.

Luckily, debugging tools can help you in the process!

Built-in Tools for Debugging

Laravel comes with some pretty neat debugging tools out of the box:


📄 Logging

Use the Log facade to send messages to log files, the system error log or other channels. You can log errors with the error method, or record details using debug().

Log::error('Error in myControllerMethod', [
    'message' => $e->getMessage(),
    'file' => $e->getFile(),
    'line' => $e->getLine(),
    'trace' => $e->getTrace(),
]);
Log::debug('This is my debug message', [
    'some_variable' => $someVariable,
    'additional_info' => 'Additional infos',
]);

🛑 Dump and Die

With the dd() function (standing for „dump and die“) you can easily investigate what is happening during execution. It lets you dump variable values at a specific point in your script to the browser, and then stop executing at that point.

dd($variable)

That way you can go through the script step by step to see where exactly things are going wrong - for example because some function is not setting the $variable value correctly.


🚧 Exception handling

Laravel records exceptions (which are errors that disrupt the flow of your app’s execution) by default, additionally to errors you log manually with Log::error. Infos about incidents are automatically written to your log files.

If you set the APP_DEBUG in your .env file to true during development (not in production!), you get more information while debugging.


🗄️ SQL query debugging

Since Laravel 10 you can use the toRawSql() / dumpRawSql() / ddRawSql() methods to inspect the SQL queries (including bindings) generated by your app using Laravel’s Eloquent ORM.

$sql = User::where('name', 'Armin')->toRawSql();
dd($sql)

// Alternatively print print the raw queries directly
User::where('name', 'Armin')->ddRawSql();
User::where('name', 'Armin')->dumpRawSql();

// select * from `users` 
// where `name` = 'Armin' 

More Debug Tools

If you want to add more options to your debugging toolbox, here are some additional recommendations for more efficiency and convenience!


➡️ Laravel Debugbar

The open-source Laravel Debugbar package provides a debug bar right in your app’s UI during development. It lets you inspect database queries, route infos, views and responses and more. You can also view log entries directly in the debug bar.

Laravel Debugbar PHP Debug Bar Integration
icon-eye-dark Created with Sketch. 5.715


➡️ Xdebug

Xdebug is an open-source debugging and profiling tool for PHP. It comes with many useful features, for example step debugging (executing your script step by step) and setting breakpoints to stop execution and inspect variables. That's very handy if you have absolutely no clue where things are going wrong yet.

Many IDEs like PhpStorm offer Xdebug extensions / integrations.


➡️ Ray

Once you have used Ray, you may not want to go back to traditional logging. (We don’t!)

Ray allows you to send logging information to its companion app in real-time, beautifully formatting your strings, arrays and objects. It also lets you filter, group and color-code your dumps.

It’s designed specifically for Laravel and can be used with Laravel and Lumen, or alongside Laravel’s Tinker REPL.

Ray Dump Debugging App
icon-eye-dark Created with Sketch. 2.116


➡️ Laravel Telescope

Laravel Telescope is an open-source debug assistant that provides a nice visual dashboard for your debugging data.

It can show insights about requests, exceptions, logs, queries, jobs, mails, notifications and more. You can configure so-called „watchers“ to tell Telescope to gather the data you need, and even extend it with custom monitors.

Laravel Telescope Elegant Debug Assistant
icon-eye-dark Created with Sketch. 1.941


➡️ Error monitoring services: Laravel Flare, Sentry & more

Error monitoring services help you catch bugs in production. They automatically report and gather insights about errors, exceptions and performance bottlenecks that occur while users are using your app.

There are many services you can choose from, depending on your app and requirements. The exception tracker Flare for example is exclusively focused on Laravel and integrates very well with the ecosystem.

Flare Error Tracker
icon-eye-dark Created with Sketch. 5.658

If you want to monitor errors across your whole stack, you might want to choose a more general-purpose platform.

Personally, we use Sentry to monitor our full-stack apps. Sentry is officially partnered with Laravel as the preferred monitoring and debugging solution for Laravel projects using Forge or Vapor, making it very easy to set up. It offers many useful features from cron job monitoring to replays of real user sessions. (As a disclaimer: Sentry is also sponsoring @MadeWithLaravel, but we’ve been using it since forever and would recommend it any time.)

With the right setup, it can help you trace a frontend error to a backend issue, connecting all parts of your app. That has saved us quite some hours and nerves! You can read a walk-through of such a debugging process on the @MadeWithVueJS blog!

Sentry for Laravel Laravel Error & Performance Monitoring
icon-eye-dark Created with Sketch. 14.066


➡️ API clients: Postman, Insomnia & more

For API development and debugging you will find it useful to have an API client at hand.

Whether you choose Postman, Insomnia or another tool – they all offer a UI for testing your endpoints, organizing requests, defining tests and monitoring your APIs. With their request builders you can easily create and send HTTP requests and view the responses.


Tips for becoming better at debugging

Being good at debugging is the most underrated skill. If you can find out where and how things are breaking, you can solve any problem. In our opinion, it’s what makes a great developer!

From experience, unsuccessful attempts at debugging often boil down to a few easy to make mistakes. Here are some tips to avoid them:

  • Read the error messages. This may sound really obvious, but many developers are so eager to solve the problem that they just skip that step, assuming they know what’s wrong.
  • Reproduce the error. Don’t assume you already know what needs to be fixed until you experienced it yourself.
  • Think broader. If you can’t find the bug in your code, think about what else could play a part in this – like an external API that doesn’t work consistently.
  • Take breaks. Not thinking about a nasty bug for a while frees up space in your brain. I promise you’ll have an idea how to fix it while making coffee or taking a walk!

If you’re still having a hard time with debugging right now, try to see it as a learning process. The more experienced you become, the more debug scenarios will feel familiar to you. A more senior developer has probably seen the kind of bug before that you’re losing your mind with - that’s why they can instantly point you to a solution.

You will learn how to debug while becoming a better developer. And as there will always be bugs, you will never stop learning 🤭