Categories
Projects

Str::wrap() macro in Laravel

While working on my personal project that is using Laravel, I was in need to write a query with a LIKE clause that searches with quotes at the beginning and end of the generated string.

While working on my personal project that is using Laravel, I was in need to write a query with a LIKE clause.

My investigations led me to an excellent post by Freek Van der Herten about implementing macro for Eloquent’s Builder class: whereLike().

But I needed my search term to be exactly like "test", with those double quotes " before and after the actual string. Using the macro suggested by Freek and looking into Laravel documentation about its Str helper class I’ve come up with this solution:

$statsModel->whereLike(
    'data_labels',
    Str::of($value)->start('"')->finish('"')
);

But I felt that there is something wrong with this excessive string. That’s just too much typing for something opposite to a regular simple trim().

And then it hit me when I opened the Illuminate\Support\Str and saw that it implements the Macroable trait: I can create my own macro!

So here it is, my first Laravel macro:

// Put it in \App\Providers\AppServiceProvider::boot().
Str::macro(
    'wrap',
    static function ($value, $wrap) {
        return Str::of($value)->start($wrap)->finish($wrap);
    }
);

I’m now able to shorten my whereLike() clause using my new Str::wrap() to just this:

$statsModel->whereLike('data_labels', Str::wrap($value, '"'));

And now I feel satisfied.

Leave a Reply

Your email address will not be published. Required fields are marked *