Custom model query builder for Laravel Eloquent

v1.0.0 2014-12-03 00:21 UTC

This package is not auto-updated.

Last update: 2021-04-12 10:28:17 UTC


Sometimes we need to extends basic query builder. Of course scopes decide many our problems, but they can't return value. For example we need to use caching query, but we must calculate/read from config/db caching time. Write it in every cahing query is not good choise. So we can define custom query builder. So, do it.


  1. Install package via composer
composer require "ed-fruty/laravel-custom-model-builder": "1.0.0"
  1. Add the service provider in app/config/app.php:
  1. Publish package configuration
php artisan config:publish ed-fruty/custom-model-builder


Now, create file app/ExampleBuilder.php and put here:


class ExampleBuilder extends Illuminate\Database\Eloquent\Builder
   * Add new method to builder
   * @access public
  public function cacheIt()
    $cacheTime = Config::get('someting.where.cache.time.saved');
    return $this->getModel()

Now register out ExampleBuilder, edit confiiguration file app/config/ed-fruty/custom-model-builder/main.php, set builderClass to ExampleBuilder Create any test model (or use existing)

class MyModel extends Eloquent
  // redeclare builder by using trait
  use Fruty\LaravelCustomBuilder\CustomBuilderTrait;

Now we can use it.

$result = MyModel::where('id', 5)->cacheIt();