2
votes

I have a problem with ordering Eloquent collection result. This is my initial code:

class Major extends Eloquent {

    protected $table = 'majors';

    /**
    * Gets all active majors
    *
    * @param $orderField Field by which the collection should be ordered
    * @param $orderDirection Direction of ordering
    */
    public static function getAllActive($orderField = 'order', $orderDirection = 'asc') {
        $columns = array('id', 'name_de', 'name_en', 'name_'.Config::get('app.locale').' as name', 'active');
        return self::all($columns)->where('active', 1);
    }
}

The method to get the majors works fine. Now, I want to order the results by a specific field, so I changed the return to this:

return self::all($columns)->where('active', 1)->orderBy($orderField, $orderDirection);

The code throws the following error:

Call to undefined method Illuminate\Database\Eloquent\Collection::orderBy()

I need to keep the $columns variable as I need the name column alias. How do I order an Eloquent result properly?

2

2 Answers

1
votes

all executes the query and returns a collection. You could use the select method:

self::whereActive(1)
    ->orderBy($orderField, $orderDirection)
    ->select($columns)
    ->get();
1
votes

Ok, figured it out. The idea is to order the collection first and then select the columns:

return self::orderBy($orderField, $orderDirection)
            ->select($columns)
            ->where('active', 1)
            ->get();

Also, Vohuman's answer is totally valid as well.