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
Like this article?
Buy me a coffee👋 Hi there! I'm Amit. I write articles about all things web development. You can become a sponsor on my blog to help me continue my writing journey and get your brand in front of thousands of eyes.