How To Define Custom Collection In Laravel With Example

admin_img Posted By Bajarangi soft , Posted On 10-09-2020

The Illuminate\Support\Collection class provides a fluent, convenient wrapper for working with arrays of data.

How To Define Custom Collection In Laravel With Example

Custom Collections

If we need to use a custom Collection object with our own extension methods, we may override the newCollection method on our model:
 

<?php

namespace App;

use App\CustomCollection;
use Illuminate\Database\Eloquent\Model;

class User extends Model
{
    /**
     * Create a new Eloquent Collection instance.
     *
     * @param  array  $models
     * @return \Illuminate\Database\Eloquent\Collection
     */
    public function newCollection(array $models = [])
    {
        return new CustomCollection($models);
    }
}
 

Once we have defined a newCollection method, we will receive an instance of our custom collection anytime Eloquent returns a Collection instance of that model. If we would like to use a custom collection for every model in our application, we should override the newCollection method on a base model class that is extended by all of our models.

To learn more about Collections In Laravel visit our Bajarangisoft site.

Related Post