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));
});
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));
});
}
}
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');
}
}
The output will be like this:
hello-world-tn8hfd
Using macros, we can create custom methods on Laravel's string helper to make string manipulation easier in a Laravel application.
Top comments (0)