animaacija
animaacija

Reputation: 180

Laravel query builder chaining

I want to define blocks of query builder within my model: So it's cunctions might be used like this:

class Transactions extends Eloquent {

public function dateRange($from,$to){
    return $this->whereBetween('date', [$from,$to]);
}

public function category($categ){
    return $this->where(['categ' => $categ]);
}
...etc , more query block functions
}

so I could chain ans reuse these, like so:

$t = new Transactions();
dd($t->category($cat)->dateRange()->get())

or as i desire ...

$t2 = new Transactions();
dd($t2->dateRange()->get()) 

This (first example of usage) will thow A Call to undefined method Illuminate\Database\Query\Builder::dateRange()

p.s. second example works, but i need to chain more than one of Qblocks to my model instance...

Upvotes: 0

Views: 1523

Answers (1)

Lancelot HARDEL
Lancelot HARDEL

Reputation: 411

Try to change your code like this:

class Transactions extends Eloquent {

    public function scopeDateRange($query, $from, $to){
        return $query->whereBetween('date', [$from, $to]);
    }

    public function scopeCategory($query, $categ){
        return $query->where(['categ' => $categ]);
    }
}

You should take a look at the query scope documentation of Eloquent : http://laravel.com/docs/5.0/eloquent#query-scopes.

Upvotes: 1

Related Questions