I have a model named “Rate” and a related controller named “RateController”. if want to make a custom query in Rate model, we could use local scope or static function like these:
using static function in the Rate model:
public static function avgerage($type, $id) { return static::where('rateble_type', $type) ->where('rateble_id', $id) ->avg('star'); }
using local scope in Rate model:
public function scopeAverageRate($type, $id, $query) { return $query->where('rateble_type', $type) ->where('rateble_id', $id) ->avg('star'); }
and finally, we call one of the above methods in the controller.
The question is, which one is the best practice? using a local scope or defining a static function in the model?
Thank you.
Advertisement
Answer
Don’t use static methods if you need the query builder.
Static methods are great for making complete queries and returning the results.
More information about Static methods on Eloquent model It will help.