Extending a Laravel collection method

90 Views Asked by At

I would like to extend the Laravel join() method. In other words, add more functionality. Just wondering how to do it. My idea is to write my own collection class that inherits from Illuminate\Support\Collection. For this I have added a new Collections folder under app (App/Collections). There I would add a new method joinWithMoreFeatures(). And from here on I don't know what to consider. My question, can someone please describe the workflow how something like this could look like?

**MyCollection**
namespace App\Collections;

class MyCollection extends Collection 
{
    public function joinWithMoreFeatures($collection)
    {
    $newFilteredCollection = $collection;
        // filter 
        return $newFilteredCollection;
    }
}

**Controller**
public function index()
{
    // How i can call the joinWithMoreFeatures() function ????
    return new MyCollection(Model::all());  
}
1

There are 1 best solutions below

5
lagbox On

You don't need to create a new class that extends from Collection and then use that class to have added functionality. The Collection class is "macroable" which is a means to extend it at run time:

use Illuminate\Support\Collection;

Collection::macro('joinWithMoreFeatures', function ($collection) {
    ...
});

You could add this to your AppServiceProvider's boot method or create a new Service Provider to handle this.

Laravel 10.x Docs - Collections - Extending Collections