ed-fruty/laravel-custom-model-builder

Custom model query builder for Laravel Eloquent

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

This package is not auto-updated.

Last update: 2024-11-19 04:00:23 UTC


README

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.

#Installation

  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:
'Fruty\LaravelModelBuilder\LaravelModelBuilderServiceProvider',
  1. Publish package configuration
php artisan config:publish ed-fruty/custom-model-builder

#Usage

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

<?php

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()
      ->remember($cacheTime)
      ->first();
  }
}

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();