Skip to content

Instantly share code, notes, and snippets.

@stayallive
Created March 22, 2023 11:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stayallive/7ab6becea0a0a3ab0443eaec22deafc4 to your computer and use it in GitHub Desktop.
Save stayallive/7ab6becea0a0a3ab0443eaec22deafc4 to your computer and use it in GitHub Desktop.
Closure alternative for Sentry options in Laravel config

Using closures in Laravel config files doesn't jive with php artisan config:cache but there is an easy alternative.

Consider the following code in your config/sentry.php:

'before_send_transaction' => function (
    \Sentry\Event $transaction
): ?\Sentry\Event {
    $ignore = ['_debugbar', 'monitoring', 'pleaseignoreme'];
    $request = $transaction->getRequest();
    $check = array_filter($ignore, function ($url) use ($request) {
        if (stripos($request['url'], $url) !== false) {
            return true;
        }
    });

    if (count($check) > 0) {
        return null;
    }

    return $transaction;
},

You can instead create a class in your application to handle this, something like app/Exceptions/Sentry.php:

<?php

namespace App\Exceptions;

use Sentry\Event;

class Sentry
{
    public static function beforeSendTransaction(Event $transaction): ?Event
    {
        $ignore = ['_debugbar', 'monitoring', 'pleaseignoreme'];
        $request = $transaction->getRequest();
        $check = array_filter($ignore, function ($url) use ($request) {
            if (stripos($request['url'], $url) !== false) {
                return true;
            }
        });

        if (count($check) > 0) {
            return null;
        }

        return $transaction;
    }
}

And update your config/sentry.php to:

'before_send_transaction' => [App\Exceptions\Sentry::class, 'beforeSendTransaction'],

And voila, php artisan config:cache works and the config file also becomes more of a config file instead of a code file 👌

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment