Laravel Custom Model Methods

前端 未结 3 998
孤街浪徒
孤街浪徒 2021-01-31 02:37

Whenever I add additional logic to Eloquent models, I end up having to make it a static method (i.e. less than ideal) in order to call it from the model\'s facade.

3条回答
  •  深忆病人
    2021-01-31 03:24

    My question is at more of a fundamental level such as why is all() accessible via the facade?

    If you look at the Laravel Core - all() is actually a static function

    public static function all($columns = array('*'))
    

    You have two options:

    public static function getAllSortedByMake()
    {
        return Car::where('....')->get();
    }
    

    or

    public function scopeGetAllSortedByMake($query)
    {
        return $query->where('...')->get();
    }
    

    Both will allow you to do

    Car::getAllSortedByMake();
    

提交回复
热议问题