Reputation: 664
I'm trying to override Eloquent's Query Builder.
I have tried the following for my MyModel
:
<?php
class CustomQueryBuilder extends Illuminate\Database\Query\Builder
{
public function get($columns = array('*'))
{
die('get');
}
}
use CustomQueryBuilder as Builder;
class MyModel extends \Illuminate\Database\Eloquent\Model
{
// the model that needs the custom query builder
}
But when I run MyModel::get()
it still returns the object instead of dying.
Any ideas how to make this work?
Upvotes: 4
Views: 3508
Reputation: 21
I think the best way to do it is :
<?php
namespace MyNamespace\Models;
use Illuminate\Database\Eloquent\Builder as BaseBuilder;
use \Illuminate\Database\Eloquent\Model;
class Builder extends BaseBuilder
{
public function like($key, $value){
return $this->orWhere($key, 'like', '%' . $value . '%');
}
}
class MyModel extends Model
{
protected $table = 'mytable';
public function newEloquentBuilder($query)
{
return new Builder($query);
}
}
Upvotes: 2
Reputation: 10003
I'm not sure exactly what you're trying to do, but at a minimum, you'll need to implement (and override) Illuminate\Database\Eloquent\Model::newBaseQueryBuilder
in your model to have it use your new Builder class.
/**
* Get a new query builder instance for the connection.
*
* @return \Illuminate\Database\Query\Builder
*/
protected function newBaseQueryBuilder()
{
$conn = $this->getConnection();
$grammar = $conn->getQueryGrammar();
return new CustomQueryBuilder($conn, $grammar, $conn->getPostProcessor());
}
Upvotes: 1