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());
}
You don't need to create a new class that extends from
Collectionand then use that class to have added functionality. TheCollectionclass is "macroable" which is a means to extend it at run time:You could add this to your
AppServiceProvider'sbootmethod or create a new Service Provider to handle this.Laravel 10.x Docs - Collections - Extending Collections