DEV Community

Ibrahim
Ibrahim

Posted on

How to Create Your Own Laravel String Helper Method Using a Macro

Laravel's String helper offers many useful methods you can use in your application.

We can also create our own laravel string helper method using a macro.

For example, I want to create a randomSlug method that turns a string into a slug and appends a random string.

use Illuminate\Support\Str;

Str::macro('randomSlug', function ($slug, $length = 6) {
    return Str::slug($slug . ' ' . Str::random($length));
});
Enter fullscreen mode Exit fullscreen mode

To use the method throughout your Laravel application, register the macro in the boot method of AppServiceProvider.

<?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Str;

class AppServiceProvider extends ServiceProvider
{
    public function register(): void {}

    public function boot(): void
    {
        Str::macro('randomSlug', function ($slug, $length = 6) {
            return Str::slug($slug . ' ' . Str::random($length));
        });
    }
}

Enter fullscreen mode Exit fullscreen mode

Here's how to use the custom helper in a controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Support\Str;

class TestController extends Controller
{

    public function test() {
        return Str::randomSlug('Hello World');
    }

}
Enter fullscreen mode Exit fullscreen mode

The output will be like this:

hello-world-tn8hfd
Enter fullscreen mode Exit fullscreen mode

Using macros, we can create custom methods on Laravel's string helper to make string manipulation easier in a Laravel application.

Top comments (0)