Mark Topper
Mark Topper

Reputation: 664

Add static function to \Illuminate\Database\Eloquent\Collection

Im trying to add a static function to Illuminate\Database\Eloquent\Collection.

I have tried the following:

Created a class:

class CustomCollection extends \Illuminate\Database\Eloquent\Collection
{
    public static function test()
    {
        die('test');
    }
}

And then I have tried including the class.

But without luck I get the error message: Call to undefined method Illuminate\Database\Eloquent\Collection::test()

The error message is given calling User::where('id', 1)->get()->test();

Upvotes: 0

Views: 815

Answers (2)

kajetons
kajetons

Reputation: 4580

To use your collection instead of the one provided by Eloquent, add a method in your model:

public function newCollection(array $models = [])
{
    // of course, adjust your namespace accordingly
    return new CustomCollection($models);
}

It will override this method in Illuminate\Database\Eloquent\Model class:

/**
 * Create a new Eloquent Collection instance.
 *
 * @param  array  $models
 * @return \Illuminate\Database\Eloquent\Collection
 */
public function newCollection(array $models = array())
{
    return new Collection($models);
}

Now every time the Eloquent queries return collection (for example, using YourModel::all()), the custom collection will be used and the methods that you added will be available.

Source: Laravel Docs

Upvotes: 3

Azeruel
Azeruel

Reputation: 210

Since i cant use the comment function i have to answer, although i dont feel like it should be flagged as an answer. Your error point out that you are calling the Collection::test().The method test in the Collection Class does not exists! You extended CustomCollection with Collection and added a method to CustomCollection not to Collection!

Upvotes: 1

Related Questions