Search

Laravel 5 Macros

April 21, 2018 —John Koster

Macros are a way to reduce the lines of code a developer has to write, and can be traditionally thought of as "shortcuts". Laravel generally uses macros to add, or inject, functionality into various classes at runtime. Developers familiar with C# can see the similarities between C#'s extension methods and Laravel's macros.

For example, the following C# will add a new method CountWords to the String class:

1namespace ExtensionExample
2{
3 public static class StringExtension
4 {
5 public static int CountWords(this String str)
6 {
7 // Implementation of CountWords in C#
8 // return word count here.
9 }
10 }
11}

Using Laravel's macros a similar end-result can be accomplished. The following example will add a countWords method to the Str support class:

1use Illuminate\Support\Str;
2 
3Str::macro('countWords', function($value)
4{
5 return str_word_count($value);
6});

#Default Classes That Support Macros

Classes allow for macros to be created by using the "\Illuminate\Support\Traits\Macroable" trait. The following table lists all of the default framework that allow for extension via macro methods:

Class
Illuminate\Auth\RequestGuard
Illuminate\Auth\SessionGuard
Illuminate\Cache\Repository
Illuminate\Console\Scheduling\Event
Illuminate\Database\Eloquent\FactoryBuilder
Illuminate\Database\Eloquent\Relations\Relation
Illuminate\Database\Query\Builder
Illuminate\Database\Schema\Blueprint
Illuminate\Filesystem\Filesystem
Illuminate\Foundation\Console\PresetCommand
Illuminate\Foundation\Testing\TestResponse
Illuminate\Http\JsonResponse
Illuminate\Http\RedirectResponse
Illuminate\Http\Request
Illuminate\Http\Response
Illuminate\Http\UploadedFile
Illuminate\Mail\Mailer
Illuminate\Routing\Redirector
Illuminate\Routing\ResponseFactory
Illuminate\Routing\Route
Illuminate\Routing\Router
Illuminate\Routing\UrlGenerator
Illuminate\Support\Arr
Illuminate\Support\Carbon
Illuminate\Support\Collection
Illuminate\Support\Optional
Illuminate\Support\Str
Illuminate\Translation\Translator
Illuminate\Validation\Rule

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.