Adding Custom Builder and Collection Methods to Laravel Models

Laravel has a neat way of adding custom builder and collection methods to your models. This is great for a smaller model and cleaner code in your controllers.

Begin with a Model

use Illuminate\Database\Eloquent\Model; 
class Homework extends Model 
{
}

Creating a Custom Builder Class

Create a new class that extends the Eloquent Builder class.

use Illuminate\Database\Eloquent\Builder; 
class HomeworkBuilder extends Builder 
{
public function whereDue()
{
$this->where('due', '=', 1);
       return $this; 
}
}

Add the Custom Builder to Your Model

Add the newEloquentBuilder function to your model and create a new instance of the builder class you created.

use Illuminate\Database\Eloquent\Model; 
class Homework extends Model 
{
public function newEloquentBuilder($builder)
{
return new HomeworkBuilder($builder);
}
}

Creating a Custom Collection Class

Create a new class that extends the Eloquent collection class.

use Illuminate\Database\Eloquent\Collection; 
class HomeworkCollection extends Collection 
{
public function whereDue()
{
$this->where('due', '=', 1);
      return $this; 
}
}

Add the Custom Collection to Your Model

Add the newCollection function to your model and create a new instance of the Collection class you created.

use Illuminate\Database\Eloquent\Model;
class Homework extends Model 
{
public function newCollection(array $models = [])
{
return new HomeworkCollection($models);
}
}

Note: Even though these functions will do the same thing, it’s good to do as much as possible within your database query (the builder). A where function in a database query will be faster than using where on a collection.


Originally published at channingdefoe.com on April 13, 2019.