Laravel adds custom method in collection using macro

what is macros in laravel. how to register custom collection method in laravel.


What is Laravel macros

Laravel macros provide a feature to add custom functionalities in laravel predefined classes. In simple words, macro is an approach to complete laravel missing functionalities.

Add custom method in laravel collection

If you want to add your method to the laravel collection then use the macro method on Collection facade. Normally we add macro method in ServiceProviders so it applies for whole application at run time. Here we will register a custom method in AppServiceProvider that change all collection value to upper case.

AppServiceProvider.php
<?php

namespace App\Providers;

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

class AppServiceProvider extends ServiceProvider
{
  public function register()
  {
    //
  }
  public function boot()
  {
    Collection::macro('toUpper', function () {
      return $this->map(function ($value) {
        return Str::upper($value);
      });
    });
  }
}

Now our custom method toUpper register and we use it on controller.

HomeController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

class HomeController extends Controller
{
  public function home() {
    $colors = collect(['black', 'red', 'white', 'yellow']);
    $colors_upper = $colors->toUpper();
    dd($colors_upper);
  }
}
php laravel developer anmol sharma

Anmol Sharma

I am a software engineer and have experience in web development technologies like php, Laravel, Codeigniter, javascript, jquery, bootstrap and I like to share my deep knowledge by these blogs.

Random tutorial links