Laravel 5

Laravel 5 Macros: Injecting Class-Based Macros With mixin


John Koster

Published on April 21, 2018

The mixin static method is used to load the methods of a mixin class instance into the target class as macro methods. The mixin method accepts a class instance as its first and only argument.


The signature of the mixin method is:

1public static function mixin(
2 $mixin

Example Use

In the following example, we will define a new string mixin class StringEncryptionMixins that will provide access to Laravel's encryption features through the Illuminate\Support\Str class:

1class StringEncryptionMixins
3 public function encrypt()
4 {
5 return function ($str) {
6 return encrypt($str);
7 };
8 }
10 public function decrypt()
11 {
12 return function ($str) {
13 return decrypt($str);
14 };
15 }

After we have defined our mixin class, we can add it to the Str class like so:

1use Illuminate\Support\Str;
3Str::mixin(new StringEncryptionMixins);

After our mixin class has been loaded into the Str class, the methods defined in the mixin class would become available via static methods of the Str class:

1use Illuminate\Support\Str;
3// Encrypt a string.
4$encrypted = Str::encrypt('string value');
6// Decrypt a string.
7$decrypted = Str::decrypt($encrypted);

Explore The Blog

The Statamic Add-on Roundup

Published on July 23, 2017

Read More