---
title: "Debugging and logging in Laravel applications"
description: "Debug Laravel apps with confidence. Learn tools, best practices, and how you can get visibility in production when logs alone aren't enough."
url: "https://blog.sentry.io/laravel-debugging-logging-guide/"
canonical_url: "https://blog.sentry.io/laravel-debugging-logging-guide/"
authors: ["Kyle Tryon"]
published: "2025-09-10"
category: "Product Updates"
---

# Debugging and logging in Laravel applications

Logic errors, failed HTTP requests, background jobs that ghost silently—software breaks in all kinds of fun ways. The difference between resilient systems and fragile ones isn’t about avoiding errors altogether. It’s about how fast and clearly you can see what went wrong, and fix it.

Laravel gives you a solid foundation: structured logging, real-time introspection, and built-in performance monitoring. You’ve got tools like `dd()`, `Log::debug()`, [Monolog](https://laravel.com/docs/12.x/logging), [Telescope](https://laravel.com/docs/12.x/telescope), [Debugbar](https://github.com/barryvdh/laravel-debugbar), and Xdebug for peering under the hood in dev and staging. But production is a different beast.

For full production visibility in both frontend and backend across errors, slowdowns, and hard-to-reproduce edge cases, [Sentry plugs into your Laravel app](https://docs.sentry.io/platforms/php/guides/laravel/) to give you the context you need, when you need it, across different services.

This guide walks through a few [Laravel debugging](https://sentry.io/resources/debug-laravel-with-sentry/) tools: what they do, when to use them, and how to get the right insights without digging through logs or guessing what went wrong across environments.

### Prerequisites

If you have Laravel 12 installed on your computer already, you can use that.

This guide uses a different approach and runs the example in a [Docker](https://docs.docker.com/get-started/get-docker) container. Using Docker guarantees that the code in this article will run on any operating system, in a secure sandbox, safely isolated from your personal files, without needing to install any specific version of Laravel, Node, or PHP.

This guide assumes you have Git installed, but you can download and unzip the example repository manually if you prefer.

## Setting up the example project

To see how Laravel’s logging and debugging tools work IRL, we’ll use a [sample payment API built with Laravel](https://github.com/getsentry/sentry-example-payment-app). The project allows users to send, receive, and convert money between currencies, and its minimal design keeps the focus on observability, not business logic. You can find the codebase here on [GitHub](https://github.com/getsentry/sentry-example-payment-app).

First, clone the project:

```bash
git clone https://github.com/getsentry/sentry-example-payment-app.git paymentApp
cd paymentApp
```

Run the command below to start a Docker terminal with Laravel 12 installed. You’ll work in this Docker terminal for the rest of the guide. If you want to run Laravel directly on your computer without Docker, skip this step.

```bash
docker run --name lara --rm -it --init -w "/app" -v .:/app -p 8000:8000 --env DB_CONNECTION=sqlite bitnami/laravel:12-debian-12 bash
```

Now run the following commands to install the dependencies and set up your environment:

```bash
cp .env.example .env;
apt update && apt install unzip 7zip;
composer install;
php artisan migrate; # choose Yes to create the database
php artisan key:generate;
```

Next, start the app:

```bash
php artisan serve --host 0.0.0.0;
```

Browse to [http://localhost:8000](http://localhost:8000/) to check that the app is running.

![laravel-welcome](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-0.C3sUVLdE.png&w=1200&q=100)

_Laravel welcome screen_

As this app is a payment **API** and not a **website**, you’ll see only the Laravel placeholder screen.

This app simply receives HTTP requests representing a payment from one user to another, and stores the payments in the database. To see how it works, look at the `app/Http/Controllers/Api/PaymentController.php` file. A function to populate the database with some sample payments is in `app/Http/Controllers/DummyDataController.php`.

## Logging Laravel applications with Monolog

By default, Laravel uses [Monolog](https://github.com/Seldaek/monolog), a powerful PHP logging library that supports multiple log formats, destinations, and severity levels. Laravel wraps the library with a clean API (like `Log::info()` and `Log::debug()`), so you can start logging without needing to understand how Monolog works.

Let’s see how you can create a log entry when a request takes more than 200 ms in your Laravel application. You’ll use [Laravel’s native database tools](https://laravel.com/docs/12.x/database#monitoring-cumulative-query-time) to detect long queries.

Push `Ctrl + C` in the terminal to stop the app running.

Overwrite the contents of `app/Providers/AppServiceProvider.php` with the following code:

```php
<?php

namespace App\Providers;

use Illuminate\Database\Connection;
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Request;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
    }

    public function boot(): void
    {
        DB::whenQueryingForLongerThan(1, function (Connection $connection, QueryExecuted $event) {
            $duration = $event->time;
            $sql = $event->sql;
            $bindings = $event->bindings;
            $connectionName = $connection->getName();

            // Information available only in HTTP contexts
            $url = '';
            $method = '';
            $ip = '';
            $userId = null;
            $requestId = uniqid();

            try {
                if (app()->runningInConsole() === false && Request::instance()) {
                    $url = Request::fullUrl();
                    $method = Request::method();
                    $ip = Request::ip();
                    $user = Request::user();
                    $userId = $user ? $user->id : null;
                }
            }
            catch (\Throwable $e) {
                Log::debug('Could not retrieve request details in slow query listener: ' . $e->getMessage());
            }

            $memoryUsage = round(memory_get_peak_usage(true) / 1024 / 1024, 2) . 'MB';

            Log::warning('Slow query detected', [
                'sql' => $sql,
                'bindings' => $bindings,
                'time' => round($duration, 2) . 'ms',
                'connection' => $connectionName,
                'url' => $url,
                'method' => $method,
                'ip' => $ip,
                'userId' => $userId,
                'requestId' => $requestId,
                'memoryUsage' => $memoryUsage,
            ]);
        });
    }

}
```

If you have a permissions issue because that file is read-only, run `sudo chown -R $USER .` in a new terminal outside of Docker to fix the file permissions.

The database measures the duration of each incoming HTTP request and logs a warning to `laravel.log` if a request takes too long. The logging entry includes metadata such as URL, method, user ID, IP address, and memory usage metrics.

Here, duration is set to 1 ms to demonstrate logging, but a more practical threshold would be 500 ms.

Let’s call the app, which will create a log entry with the new middleware.

Restart the app:

```bash
php artisan serve --host 0.0.0.0;
```

In a **new** terminal on your host (**not in Docker**, where the app is still running), call the app to generate dummy log data:

```bash
curl -X POST http://localhost:8000/api/v1/generate-dummy-data -H "Content-Type: application/json" -H "Accept: application/json"
```

In the same host terminal, run the following command to view the logs:

```bash
cat storage/logs/laravel.log
```

The log output shows that one slow log was detected.

```bash
[2025-07-21 15:39:21] local.WARNING: Slow query detected {"sql":"insert into \"users\" (\"name\", \"email\", \"password\", \"updated_at\", \"created_at\") values (?, ?, ?, ?, ?)","bindings":["Dummy User 7","dummy.user6.1753112360@example.com","$2y$12$HGWsD0hK6AmyUcQrZa4aHuBI7yNoITX5UUwL5PWQQ2gENYsUrKPNW","2025-07-21 15:39:21","2025-07-21 15:39:21"],"time":"0.1ms","connection":"sqlite","url":"http://localhost:8000/api/v1/generate-dummy-data","method":"POST","ip":"172.17.0.1","userId":null,"requestId":"687e5f29c31ce","memoryUsage":"10MB"}
```

### Use Channels to Control Log Destinations

Laravel’s logging system is channel-based. Each channel defines a driver (for example, `stack`, `daily`, `slack`, or `syslog`) and configuration for how and where logs are written. You define and customize logging channels in `config/logging.php`.

The default channel is typically stack, which lets you combine multiple channels into one:

```php
// config/logging.php

'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['daily', 'slack'],
        'ignore_exceptions' => false,
    ],

    'daily' => [
        'driver' => 'daily',
        'path' => storage_path('logs/laravel.log'),
        'level' => 'debug',
        'days' => 14,
    ],

    'slack' => [
        'driver' => 'slack',
        'url' => env('LOG_SLACK_WEBHOOK_URL'),
        'username' => 'Laravel Log',
        'emoji' => ':boom:',
        'level' => 'critical',
    ],
]
```

You can change the active logging channel in the `.env` file to specify where logs are written (for example, to a log file or to a channel on Slack):

```bash
LOG_CHANNEL=stack
```

Using a stack ensures that logs can be written to multiple destinations simultaneously. For example, you can write debug output to a file while also sending critical errors to Slack or Sentry.

## Which tools to use for debugging Laravel applications

Logging helps you capture what went wrong, but it doesn’t always tell you why. For deeper insight into issues, you need debugging tools that help you trace requests, examine queries, and understand failures.

Laravel provides a range of tools you can use for debugging locally or investigating deeper issues:

-   The `dd()` and `dump()` functions: To inspect variables, objects, and execution flow on the fly.
-   Laravel Telescope: For deeper visibility, such as tracking SQL queries, measuring request duration, or understanding why a job failed.
-   Laravel Debugbar: To track rendered views, route details, query execution time, and memory usage.

### Laravel’s built-in debugging functions — `dd()` and `dump()`

Often, the first step in debugging is seeing what a variable contains. Laravel provides two built-in helpers for this:

-   `dump()` outputs the variable contents but **continues** execution.
-   `dd()` (short for “dump and die”) outputs the data and **terminates** the request.

For example, you can log information about requests for payment creation, and have `dd()` under a `catch` block to analyze and handle exception details better.

In `app/Http/Controllers/Api/PaymentController.php`, overwrite the store function with the following code:

```php
public function store(PaymentRequest $request): JsonResponse
{
    try {
        $payment = Payment::create($request->validated());

        // Debug: Check the created payment
        dump('Created payment:', $payment->toArray());

        // Raise error for testing
        // throw new \Exception('Test error');

        return response()->json(['data' => $payment], 201);
    }
    catch (\Exception $e) {
        // Debug: Check the exception details
        dd('Payment creation failed:', [
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);
        return response()->json(['error' => 'Failed to create payment'], 500);
    }
}
```

Now when you use an API client to send a `POST` request to create a payment, you will see the output in the response panel.

In the terminal on your host (**not** in the Docker terminal), run the command below to send a payment through the app:

```bash
curl -X POST 'http://localhost:8000/api/v1/payments' \
--header 'Content-Type: application/json' \
--data '{
  "amount":      100,
  "currency":    "USD",
  "type":        "send",
  "sender_id":   1,
  "receiver_id": 2
}'
```

The command output will look confusing. This is because dump commands return debug information to the browser, not to the terminal running the app or a log file.

Use a visual request sender like [Insomnia](https://insomnia.rest/download) to format the output understandably.

![Making a request to the application using the API clientInsomnia](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-1.wJYfNchX.jpg&w=1200&q=100)

_Making a request in Insomnia_

The `dd()` and `dump()` functions are powered by Symfony’s VarDumper component, so you get clean, readable output even for complex objects and collections.

That said, `dd()` or `dump()` should **never** be included in production code. Those tools stop execution, leak internals, and aren’t logged. For production-safe inspection, it’s better to use structured logging like `Log::debug()`.

### Using Laravel Debugbar effectively

[Laravel Debugbar](https://github.com/barryvdh/laravel-debugbar) adds a visual toolbar to your application, displaying debugging information directly in the browser. Debugbar integrates tightly with Laravel and gives you instant feedback on what’s happening behind the scenes. It’s ideal for frontend-heavy development or when you want to inspect queries, routes, and request timing directly on the pages you’re developing.

You can install the package using Composer.

Push Ctrl C in the Docker terminal to stop the app running.

Run the following commands to install Debugbar and restart the app:

```bash
composer require barryvdh/laravel-debugbar --dev;
php artisan serve --host 0.0.0.0;
```

Once installed, Debugbar activates automatically and appears as a floating bar at the bottom of any page your app renders. The image below shows the root page of the Laravel application running at [http://127.0.0.1:8000](http://127.0.0.1:8000/).

![A red arrow pointing out the debug bar from Laravel Debugbar at the bottom if the application window](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-2.Cd6DRuWW.png&w=2048&q=100)

_Laravel Debugbar_

You can inspect the queries executed on this page before the content is rendered.

![A red arrow pointing out the "Queries" tab in Debugbar](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-3.CDm2es3_.png&w=2048&q=100)

_Laravel Debugbar SQL Queries_

Debugbar is great for local development, especially when you’re dealing with [Eloquent](https://laravel.com/docs/12.x/eloquent) performance issues, trying to understand route behavior, or debugging composition issues. Like Laravel’s built-in helpers, Debugbar is not meant for production use. Keep it in your dev dependencies and disable it outside of local environments.

### How to set up Laravel Telescope

[Laravel Telescope](https://laravel.com/docs/telescope) is an official debugging assistant that gives you deep visibility into your application’s runtime behavior. Useful during local development or when debugging in a staging environment, Telescope acts as a dashboard for your backend, displaying incoming requests, queued jobs, exceptions, logs, and database queries in real time.

Push `Ctrl + C` in the Docker terminal to stop the app running.

Run the following commands to install Telescope:

```bash
composer require laravel/telescope --dev;
php artisan telescope:install;
php artisan migrate;
php artisan serve --host 0.0.0.0;
```

You’ll find the Telescope UI panel at [http://localhost:8000/telescope](http://localhost:8000/telescope).

![A screenshot showing the UI for Telescope, currently on the "Requests" tab.](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-4.DroCTZmp.png&w=2048&q=100)

_Telescope UI_

Once enabled, Telescope will automatically record details such as:

-   HTTP requests (including headers, payloads, and status codes)
-   Database queries (with bindings and execution time)
-   Logs
-   Scheduled tasks
-   Queued jobs
-   Model events

With Telescope, you can inspect the code without modifying it, giving you enough context to understand the situation and make informed decisions. For example, here is a detailed view of a `POST` request to `/api/v1/payments`.

![Telescope showing a detailed view of a request, with info like its details, the payload, and queries.](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-5.BvA8uVRS.png&w=2048&q=100)

_Request detailed view_

Avoid running Telescope in production unless it’s secured, as it exposes sensitive data. Even then, it isn’t optimized for production environments: Telescope logs everything, which can add performance overhead.

### Best practices for Debugging Laravel in VS Code

For low-level inspection and stepping through code line by line, Xdebug remains the most potent option for debugging Laravel applications in VS Code. With Xdebug, you can set breakpoints, watch variables, and control execution flow, all from your editor.

Laravel supports Xdebug out of the box, and if you’re using [Laravel Sail](https://laravel.com/docs/sail), [DDEV](https://ddev.readthedocs.io/), or another containerized environment, enabling Xdebug is typically a matter of flipping a config flag.

When Xdebug is set up in VS Code, you can:

-   Pause execution inside a controller method or job handler to inspect what’s happening line-by-line.
-   Inspect objects, closures, and service container bindings.
-   Watch runtime state across the request and response lifecycle.

Learn more about debugging with Xdebug and VS Code in our post on [logging and debugging in PHP](https://blog.sentry.io/how-to-debug-and-log-in-php/#debug-in-vs-code).

## Troubleshooting and fix performance issues in a Laravel app

Laravel’s logging and debugging tools can also help uncover performance issues – especially during development.

-   **Monolog:** Add logging to middleware, listeners, or other performance-critical areas of your application to track slow SQL queries and identify bottlenecks.
-   **Laravel Telescope:** Monitor components that impact performance. On the **Queries** page, for example, you can see how long each query takes, identify slow ones, and dig into the details to understand what’s causing delays.

![The queries tab in Telescope , showing a list of the different queries and their duration.](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-6.Ds0Y7MBu.png&w=1200&q=100)

_Laravel Telescope Queries page_

-   **Laravel Debugbar:** Inspect what’s happening behind the scenes of your web pages. Use the timeline view to analyze query performance, track events, and see how long each part of the page takes to render.

![Debugbar, highlighting the Timeline tab and the different events with their order and duration.](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-7.BMCuKtOt.png&w=2048&q=100)

_Laravel Debugbar Timeline graph_

However, these tools work best when you are already aware of performance issues and you are debugging them locally. In production, troubleshooting requires a different approach. Monolog can log issues, but it won’t notify you in real time. Telescope and Debugbar give you deep insight, but they track everything and aren’t designed to run safely in production.

For troubleshooting and fixing performance issues in production, you need to:

-   Be alerted when processes are slow.
-   See stack traces and exception context in real time.
-   Track which environments are affected.
-   Measure impact by seeing how many users are affected, how often, and which endpoints or views are involved.

## Debugging and logging Laravel in production with Sentry

Effective debugging requires knowing when your application breaks, why it happens, and what context led to the failure. This is where [Sentry](https://sentry.io/resources/debug-laravel-with-sentry/) fills the gap: It captures unhandled exceptions, aggregates similar errors, displays full stack traces, and automatically adds context such as environment, route, user, and release version.

Integrating Sentry into a Laravel application is straightforward using the [Sentry Laravel SDK](https://sentry.io/for/laravel/). Review the complete [PHP SDK documentation](https://docs.sentry.io/platforms/php/) for more advanced integration options and platform support.

### **Install Sentry and monitor errors**

To install Sentry in the Laravel app, you’ll use the code snippets given in the [Sentry Laravel guide](https://docs.sentry.io/platforms/php/guides/laravel/).

Push `Ctrl + C` in the Docker terminal to stop the app running.

Install the Sentry SDK with the following command:

```bash
composer require sentry/sentry-laravel
```

Overwrite the contents of `bootstrap/app.php` with the following code to enable Sentry to capture unhandled exceptions:

```php
<?php

use Illuminate\Foundation\Application;
use Illuminate\Foundation\Configuration\Exceptions;
use Illuminate\Foundation\Configuration\Middleware;
use Sentry\Laravel\Integration;

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        commands: __DIR__.'/../routes/console.php',
        api: __DIR__.'/../routes/api.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //
    })
    ->withExceptions(function (Exceptions $exceptions) {
        Integration::handles($exceptions);
    })
    ->create();
```

Because the payment gateway you’re working on is an API and not a website, the code above includes one line not in the Sentry Laravel guide: `api: __DIR__.'/../routes/api.php',`.

Next, [create a new Laravel project in Sentry](https://sentry.io/projects/new) and take note of the project’s DSN in the Sentry dashboard.

In the Docker terminal, run the following command to configure Sentry, replacing YOUR\_DSN with your project’s DSN:

```bash
php artisan sentry:publish --dsn=YOUR_DSN
```

Answer `yes` to all prompts.

This creates a `config/sentry.php` file, adds the DSN to your `.env` file with the variable name `SENTRY_LARAVEL_DSN`, and sends a test error to Sentry.

Now run the following command to send another test error to Sentry and verify the configuration:

![A terminal window with lines showing that a test event has been sent with an ID.](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-8.DXVntUze.png&w=1200&q=100)

_Sentry configuration test_

Click **Issues** in the sidebar of the Sentry web interface. The **Issues** page displays the test errors.

![The Sentry dashboard with the Issue feed visible, showing two new exceptions.](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-9.Cudk2V7j.png&w=2048&q=100)

_Test issues with Sentry_

Sentry is now set up to monitor your application and log any new issues

### Manually report errors

You can also manually report caught exceptions to Sentry.

For example, consider the payment creation endpoint you altered with the dump function in `app/Http/Controllers/Api/PaymentController.php`.

```php
public function store(PaymentRequest $request): JsonResponse
{
    try {
        $payment = Payment::create($request->validated());

        // Debug: Check the created payment
        dump('Created payment:', $payment->toArray());

        // Raise error for testing
        // throw new \Exception('Test error');

        return response()->json(['data' => $payment], 201);
    }
    catch (\Exception $e) {
        // Debug: Check the exception details
        dd('Payment creation failed:', [
            'error' => $e->getMessage(),
            'trace' => $e->getTraceAsString()
        ]);

        return response()->json(['error' => 'Failed to create payment'], 500);
    }
}
```

Instead of using `dump()`, you can report the exception to Sentry.

Overwrite the `store` function with the following code to implement Sentry error reporting:

```php
public function store(PaymentRequest $request): JsonResponse
{
    try {

        $payment = Payment::create($request->validated());
        // Raise error for testing
        throw new \Exception('Payment test error');

        return response()->json(['data' => $payment], 201);
    }
    catch (\Exception $e) {
        // Log the error with Sentry
        \Sentry\captureException($e);

        return response()->json(['error' => 'Failed to create payment'], 500);
    }
}
```

Now when a request is made to create a payment, it will result in a 500 error, and Sentry will capture the exception.

Start the app in the Docker terminal:

```bash
php artisan serve --host 0.0.0.0;
```

In a terminal on your host, create an error by calling the app with curl:

```bash
curl -X POST 'http://localhost:8000/api/v1/payments' \
--header 'Content-Type: application/json' \
--data '{
  "amount":      100,
  "currency":    "USD",
  "type":        "send",
  "sender_id":   1,
  "receiver_id": 2
}'
```

Refresh the Sentry **Issues** page in your browser to see the error.

![A new issue shows up in Sentry](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-10.C1ZiQD-7.png&w=2048&q=100)

_Sentry capturing payment error_

Click on the issue to see more information about the exception.

The detailed trace with the lines causing the error is shown at the top of the page.

![In the Sentry Stack Trace UI, the line causing the error is highlighted with a red arrow](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-11.Xgz19CfJ.png&w=2048&q=100)

_Issue trace_

Scroll down to see information about the request, including the body, header, and metrics like server response time.

![The sentry UI, showing the trace preview and http request info.](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-12.DTZSzL-d.png&w=2048&q=100)

_Sentry trace view_

Once you have basic exception tracking working, you can further customize how errors are organized and surfaced.

Sentry allows you to tag issues with custom data, such as the environment (local, staging, or production), the authenticated user ID, or specific application states. This helps you group and filter issues effectively, especially in multi-tenant or multi-service systems.

### Sending structured logs

Sentry can store logs from your app in a structured format.

Read an [overview of this feature](https://docs.sentry.io/product/logs/) or [how to set it up in Laravel](https://docs.sentry.io/platforms/php/guides/laravel/logs/). For a language-agnostic walkthrough, see how to [structure your logs for faster debugging](https://sentry.io/cookbook/structure-your-logs/).

This section demonstrates how to configure structured logs in Laravel.

In `config/logging.php`, add the new `sentry_logs` channel to the `channels` array at about line 53, to match the following code snippet:

```php
'channels' => [
    'sentry_logs' => [
        'driver' => 'sentry_logs',
        'level' => env('LOG_LEVEL', 'info'),
    ],
```

In the `.env` file, add `,sentry_logs` to the `LOG_STACK` setting to enable the new driver, and enable the Sentry log setting. Use the lines below as reference.

```shell
LOG_STACK=single,sentry_logs
SENTRY_ENABLE_LOGS=true
```

If you don’t have permissions to save the file, you might need to run the chown command from earlier in this guide.

In `app/Http/Controllers/Api/PaymentController.php`, alter the store function one last time to send some logs to Sentry.

Near the top of the controller file in the using section, add the following line:

```php
use Illuminate\Support\Facades\Log;
```

Further down in the file, overwrite the store function with the following code:

```php
public function store(PaymentRequest $request): JsonResponse
{
    try {
        $payment = Payment::create($request->validated());
        Log::info(
            'Payment {paymentId} for {paymentAmount} {paymentCurrency} created for user {userId} from {ipAddress} via {requestMethod} {requestUrl}',
            [
                'paymentId' => $payment->id,
                'paymentAmount' => $request->validated('amount'),
                'paymentCurrency' => $request->validated('currency'),
                'userId' => $request->user()?->id,
                'ipAddress' => $request->ip(),
                'requestMethod' => $request->method(),
                'requestUrl' => $request->fullUrl(),
                'validatedData' => $request->validated(),
                'requestId' => $request->header('X-Request-ID') ?? uniqid(),
            ]
        );
        return response()->json(['data' => $payment], 201);
    }
    catch (\Exception $e) {
        \Sentry\captureException($e);
        return response()->json(['error' => 'Failed to create payment'], 500);
    }
}
```

This new code logs both plain text and structured properties at the info severity level.

Push Ctrl C in the Docker terminal to stop the app.

Restart the app:

```bash
php artisan serve --host 0.0.0.0;
```

▶️ In the terminal on your host (not in the Docker terminal), run the following command to send a payment through the app:

```bash
curl -X POST 'http://localhost:8000/api/v1/payments' \
--header 'Content-Type: application/json' \
--data '{
  "amount":      2000,
  "currency":    "USD",
  "type":        "send",
  "sender_id":   1,
  "receiver_id": 2
}'
```

▶️ Wait a moment for Sentry to receive the log, then browse to the **Logs** tab in the Sentry web interface to see the log details.

![The Sentry Logs tab, highlighting the latest payment](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-13.CetMHUiI.png&w=2048&q=100)

_Sentry structure logs for Laravel_

You can filter Sentry logs by text, property, severity level, timestamp, or structured properties (like currency) to find more information about an error.

### Handle logins

To have Sentry automatically associate logged-in users with events, add this setting to the `.env` file:

```bash
SENTRY_SEND_DEFAULT_PII=true
```

For more control over how and when authentication is logged, manually set the user by listening to Laravel’s `Authenticated` event.

Since this example payment API doesn’t use authentication, there’s no authentication activity to log. However, to add Sentry authentication logging to a Laravel app that does use authentication, overwrite the contents of `app/Providers/AppServiceProvider.php` with the following code:

```php
<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Event;
use Illuminate\Auth\Events\Authenticated;
use Sentry\State\Scope;
use Sentry\Laravel\Integration;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Event::listen(function (Authenticated $event) {
            $user = $event->user;

            Integration::configureScope(static function (Scope $scope) use ($user): void {
                $scope->setUser([
                    'id' => $user->id,
                    'name' => $user->name,
                    'email' => $user->email,
                ]);
            });
        });
    }
}
```

### Add custom tags to events

With Sentry, you can enrich events by adding custom tags — indexed key-value pairs that you can use to group, search, and filter issues. Tags can track details like locale, customer tier, deployment version, or request source.

```php
\Sentry\configureScope(function (\Sentry\State\Scope $scope): void {
    $scope->setTag('tenant', 'acme-corp');
    $scope->setTag('page.locale', 'en-us');
});
```

Learn more about enriching events in Sentry’s [Laravel documentation](https://docs.sentry.io/platforms/php/guides/laravel/enriching-events/).

### Automatically detect poor performance

Sentry also enables you to track performance issues related to specific events in your project. For example, you can configure Sentry to alert you about slow database queries or N+1 requests. To fine-tune Sentry alerts, go to **Settings → Projects → \[Your Project\] → Performance** in your dashboard. All configuration options are under **Performance Issues – Detector Threshold Settings**.

![laravel-performance-detector](https://blog.sentry.io/_vercel/image?url=_astro%2Finline-14.CFgEUR7S.png&w=1920&q=100)

_Sentry performance configuration_

For solutions to common Laravel issues in both production and development environments, our [Sentry Laravel Answers page](https://sentry.io/answers/laravel/) can answer common problems. For broader PHP error-handling guidance, check out our [Sentry PHP Answers hub](https://sentry.io/answers/php/).

### Cleaning up

If you need some help cleaning up everything we just went through, here’s how you delete and remove the example repo:

Close the Docker terminal by typing `exit`.

Then run the following commands to delete all the Docker images from your system and remove the example repository:

```bash
docker stop lara;
docker rm lara;
docker images rm bitnami/laravel:12-debian-12;
cd ..
rm -rf paymentApp
```

### See what’s slowing down your Laravel app—before your users do.

Insights for your Laravel project connects the dots between routes, jobs, queries, and cache usage, so you can fix what matters faster.

[Monitoring & Insights for Laravel](https://blog.sentry.io/laravel-just-works-now-your-performance-monitoring-does-too/)

## Debug Laravel smarter, not harder

Laravel’s approach to monitoring and debugging is developer-friendly. Whether you’re using `dd()` to print a variable or Telescope to analyze a failed request, you’re working with tools designed to support developer productivity.

But most of those tools are optimized for development environments. Yes, you can configure Telescope for production, but you’ll need to secure it, manage access, and handle the performance implications. Laravel’s `dd()` and `dump()` functions offer instant visibility, but easily leak data and halt execution if used in the wrong context. Monolog provides structured logging, which is crucial for audit trails, but it lacks real-time insights and alerting capabilities.

In production, where real-time visibility, fast response times, and issue grouping across environments and user sessions are required, those limitations become apparent. You need to know something’s broken before your users report it, and that’s where [Sentry](https://sentry.io/for/laravel/) stands out. Sentry integrates cleanly into Laravel, captures rich context across both frontend and backend, and extends your logging setup with structured logs that live alongside your error data. That means you can filter by severity, search across properties, and correlate logs with stack traces, user IDs, and releases.
