Amit Merchant

Amit Merchant

A blog on PHP, JavaScript, and more

A Laravel macro for outputting possessive apostrophes correctly

Macros in Laravel are gifts that keep on giving. They let you extend the functionality of Laravel in a way that you can use them anywhere in your application.

So, I recently came across a tweet by Alex Garrett-Smith which shows a pretty handy macro using which you can output possessive apostrophes in Laravel.

Here’s the macro in question.

use Illuminate\Support\Str;

Str::macro('possessive', function ($string) {
    return $string . '\'' . (
        Str::endsWith($string, ['s', 'S']) ? '' : 's'

echo Str::possessive('Cherika'); // Cherika's
echo Str::possessive('James'); // James'

As you can see, the macro takes a string and appends an apostrophe (') to it. But, if the string ends with s or S, it doesn’t append the apostrophe.

That’s a pretty handy macro, isn’t it?

You may like: Estimated reading time macro in Laravel

Learn the fundamentals of PHP 8 (including 8.1 and 8.2), the latest version of PHP, and how to use it today with my new book PHP 8 in a Nutshell. It's a no-fluff and easy-to-digest guide to the latest features and nitty-gritty details of PHP 8. So, if you're looking for a quick and easy way to PHP 8, this is the book for you.

👋 Hi there! I'm Amit. I write articles about all things web development. If you like what I do and want me to continue doing the same, I'd like you consider leaving a tip. I'd highly appreciate that. Cheers!