Backend Development 8 min read

Laravel Mixins: Extending Str and Arr Helpers with Macros

This guide explains how to use Laravel macros and Mixins to extend the Str and Arr helper classes, providing reusable methods such as fullName, initials, camelToSnake, snakeToCamel, and filterNulls, and demonstrates registration via AppServiceProvider for cleaner, maintainable backend code.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Laravel Mixins: Extending Str and Arr Helpers with Macros

Welcome to a Laravel Mixins tutorial that first introduces Laravel macros, which allow you to add custom methods to classes like Str and Arr for better code reuse and organization.

Using macros, you can define methods such as fullName , initials , camelToSnake , snakeToCamel , and filterNulls directly in the boot method of AppServiceProvider :

<?php

namespace App\Providers;

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

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     */
    public function boot(): void
    {
        Str::macro('fullName', function (string $firstname, string $lastname) {
            return trim($firstname . ' ' . $lastname);
        });

        Str::macro('initials', function (string $firstname, string $lastname) {
            return strtoupper($firstname[0] . $lastname[0]);
        });

        Arr::macro('camelToSnake', function (array $array) {
            return Arr::mapWithKeys($array, function ($value, $key) {
                return [Str::snake($key) => $value];
            });
        });

        Arr::macro('snakeToCamel', function (array $array) {
            return Arr::mapWithKeys($array, function ($value, $key) {
                return [Str::camel($key) => $value];
            });
        });

        Arr::macro('filterNulls', function (array $array) {
            return Arr::where($array, function ($value) {
                return !is_null($value);
            });
        });
    }
}

Laravel’s Macroable classes let you extend functionality, but registering many separate providers can become cumbersome. Mixins provide a cleaner, more maintainable alternative by grouping related macros into dedicated classes.

What is a Mixin?

A Mixin is similar to a macro; it is a class that contains methods you want to mix into another class. Each method must be public or protected , have no parameters, and return a Closure that encapsulates the actual logic.

Create a Mixins directory and add two classes: StringMixin and ArrayMixin .

ArrayMixin.php

<?php

namespace App\Mixins;

use Closure;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;

class ArrayMixin
{
    /**
     * @return Closure
     */
    public function camelToSnake()
    {
        return function (array $array) {
            return Arr::mapWithKeys($array, function ($value, $key) {
                return [Str::snake($key) => $value];
            });
        };
    }

    /**
     * @return Closure
     */
    public function snakeToCamel()
    {
        return function (array $array) {
            return Arr::mapWithKeys($array, function ($value, $key) {
                return [Str::camel($key) => $value];
            });
        };
    }

    /**
     * @return Closure
     */
    public function filterNulls()
    {
        return function (array $array) {
            return Arr::where($array, function ($value) {
                return !is_null($value);
            });
        };
    }
}

StringMixin.php

<?php

namespace App\Mixins;

use Closure;

class StringMixin
{
    /**
     * @return Closure
     */
    public function fullName()
    {
        return function (string $firstname, string $lastname) {
            return trim($firstname . ' ' . $lastname);
        };
    }

    /**
     * @return Closure
     */
    public function initials()
    {
        return function (string $firstname, string $lastname) {
            return strtoupper($firstname[0] . $lastname[0]);
        };
    }
}

Register the mixins in AppServiceProvider :

/**
 * Bootstrap any application services.
 */
public function boot(): void
{
    Str::mixin(new StringMixin());
    Arr::mixin(new ArrayMixin());
}

Using Mixins keeps your project organized, improves readability, and simplifies maintenance. If the number of mixins grows, consider creating a dedicated MixinServiceProvider to further streamline registration.

Advantages of Mixins

Improves code reusability by encapsulating common helper logic that can be used across the application.

Maintains clean core classes, allowing them to focus on primary responsibilities while auxiliary methods reside in mixin classes.

Enhances maintainability; changes to helper logic are made in a single mixin class rather than scattered throughout the codebase.

backendphpcode reuseMacrosLaravelmixins
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.