Callum
Callum

Reputation: 1165

Laravel Custom Eloquent Method

I have been building queries and repeating code, is there a way to build this into the eloquent model?

I have a model Transaction where I am selecting specific currencies. How can I add this into the model? Is there a way of changing this:

Transaction::select('*')->where('currency', '=', 'GBP')

So that I can do this:

Transaction::select('*')->currency('GBP')

Then in the model it adds onto the query somehow. I've tried to create Transaction::currency but it didn't work. This is just an example and I plan on adding a few selectors to keep the code clean.

class Transaction extends Model
{
    protected $table = 'transactions';


    public function currency($query, $currency) {
      return $query->where('currency', '=', $currency);
    }
}

Upvotes: 1

Views: 260

Answers (4)

mezoo-adel
mezoo-adel

Reputation: 29

After 7 years of your question there's now a new syntax by Laravel

Model::whereColumn('value')->get();

Transaction::whereCurrency('GBP')->get();

Upvotes: 0

Abdullah Al Shakib
Abdullah Al Shakib

Reputation: 2044

You can do this by using scope.

Add these code to Transaction.php file

public function scopeCustom($query, $column, $exp, $value)
{
    return $query->where('votes', $exp, $value);  // ('currency', '=', 'GBP')
}

Now use this scope as like

Transaction::select('*')->custom('currency', '=', 'GBP');
Transaction::select('*')->custom('amount', '>', 1000); 

Upvotes: 0

unxp
unxp

Reputation: 358

Laravel has such thing called Query Scopes. It allows you to do exactly what you want. You just need to prefix your currency() method with scope keyword like this:

class Transaction extends Model
{
    protected $table = 'transactions';


    public function scopeCurrency($query, $currency) {
      return $query->where('currency', '=', $currency);
    }
}

Then you can do this Transaction::select('*')->currency('GBP')

Read more about scopes here

Upvotes: 1

Imtiaz Pabel
Imtiaz Pabel

Reputation: 5443

you are almost done,you have to write currency method as query scope.

public function scopeCurrency($query, $currency) {
  return $query->where('currency', '=', $currency);
}

after doing that you can use scope like this

Transaction::select('*')->currency('GBP')

For more details go here https://laravel.com/docs/5.2/eloquent#local-scopes

Upvotes: 1

Related Questions