Black Friday: the Laravel testing course is $149 instead of $249, through Dec 7. See the course →
logo

Where should I put this class?

Maybe nowhere

Joel Clermont
Joel Clermont
2025-09-25

From our daily Laravel tips email. Get the next one in your inbox.

We were working on a project which used the spatie/laravel-ciphersweet package to transparently encrypt and decrypt certain fields in our database.

The underlying CipherSweet php package comes with some common transformations, like LastFourDigits, which is useful for encrypting numeric strings while still allowing you to search by the last four digits.

I had a specific need for a LastFourCharacters transformation, which would work for any string, not just numeric strings. The way to do this was to build a new Transformation class that implemented a specific interface.

I built it, and it was working, but I wasn't quite sure where this class should go in our Laravel app. After coming up with an initial location, I asked Aaron what he thought, and I loved his answer: "If it's just one class - can you just make it anonymous?"

Not only was the class implementation only four lines, it was only used in this one model, so why worry about where to put it? Just keep it inline the one place it's needed. This was a great suggestion!

Here's what it looked like in practice:

// in the model's configureCipherSweet method
$encryptedRow->addBlindIndex('drivers_license', new BlindIndex('drivers_license_last4_index', [
    new class implements TransformationInterface
    {
        public function __invoke(#[SensitiveParameter] mixed $input): string
        {
            $input = (string) $input;
            $input = str_pad($input, 4, ' ', STR_PAD_LEFT);

            return Binary::safeSubstr($input, -4, 4);
        }
    },
]));

Here to help,

Joel

P.S. Another great place to bounce ideas off smart developers is the Mastering Laravel community.

Want a tip like this in your inbox every weekday?

Each one takes less than 2 minutes to read. Join 4,000+ Laravel developers who already get them.

email
No spam. Only real-world advice.
Toss a coin in the jar if you found this helpful.