ADDING METHODS TO LARAVEL VIRTUALLY
Feb 22, 2024 Copy Link
Let's imagine that you need to change the coming value to make the first capital letter of every word and then append hyphens between the words, in this case, you may write your code into a separate function and then call it, but, using Laravel it's a primitive way because it let you add your whatever logic into built-in Laravel classes via `macro`
method:
namespace App\Providers;
use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Str::macro('slugTitleCase', function ($value) {
return str_replace(' ', '-', ucwords($value));
});
}
}
After that, you can use the injected method:
use Illuminate\Support\Str;
Str::slugTitleCase('welcome macro world'); // Welcome-Macro-World
But, what if you need to inject multi-methods into the `Str`
class, you will never repeat your code many times instead you should use the `mixin`
method:
namespace App\Providers;
use App\Classes\StrMacro;
use Illuminate\Support\Str;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Str::mixin(new StrMacro);
}
}
Then you can append all methods that you need into the `StrMacro`
class:
namespace App\Classes;
use Closure;
class StrMacro
{
/**
* Change the coming string to slug title case.
*/
public function slugTitleCase(): Closure
{
return function ($value) {
return str_replace(' ', '-', ucwords($value));
};
}
}
Also, the way of use is still fixed 🕵️♂️