Illuminate\Database\Query\Builder::aggregate PHP Method

aggregate() public method

Execute an aggregate function on the database.
public aggregate ( string $function, array $columns = ['*'] ) : mixed
$function string
$columns array
return mixed
    public function aggregate($function, $columns = ['*'])
    {
        $this->aggregate = compact('function', 'columns');
        $previousColumns = $this->columns;
        // We will also back up the select bindings since the select clause will be
        // removed when performing the aggregate function. Once the query is run
        // we will add the bindings back onto this query so they can get used.
        $previousSelectBindings = $this->bindings['select'];
        $this->bindings['select'] = [];
        $results = $this->get($columns);
        // Once we have executed the query, we will reset the aggregate property so
        // that more select queries can be executed against the database without
        // the aggregate value getting in the way when the grammar builds it.
        $this->aggregate = null;
        $this->columns = $previousColumns;
        $this->bindings['select'] = $previousSelectBindings;
        if (!$results->isEmpty()) {
            return array_change_key_case((array) $results[0])['aggregate'];
        }
    }

Usage Example

Example #1
0
 /**
  * Execute an aggregate function on the database.
  *
  * @param  string  $function
  * @param  array   $columns
  * @return mixed
  */
 public function aggregate($function, $columns = array('*'))
 {
     // Postgres doesn't like ORDER BY when there's no GROUP BY clause
     if (!isset($this->groups)) {
         $this->reOrderBy(null);
     }
     return parent::aggregate($function, $columns);
 }
All Usage Examples Of Illuminate\Database\Query\Builder::aggregate