Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override Eloquent Query Builder

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?

like image 877
Mark Topper Avatar asked Aug 30 '25 18:08

Mark Topper


1 Answers

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);
    }
} 
like image 99
Ti Tiaso Avatar answered Sep 02 '25 08:09

Ti Tiaso