To count, max, min, avg, and sum of the data in table
SQL count() Syntax
SELECT COUNT(column_name)
FROM table_name
WHERE condition;
SQL min() Syntax
SELECT MIN(column_name)
FROM table_name
WHERE condition;
SQL max() Syntax
SELECT MAX(column_name)
FROM table_name
WHERE condition;
SQL avg() Syntax
SELECT AVG(column_name)
FROM table_name
WHERE condition;
SQL sum() Syntax
SELECT SUM(column_name)
FROM table_name
WHERE condition;
How can you use aggregates function in laravel
Let's seeYou may also use the count, sum, max, and other aggregate methods provided by the query builder. These methods return the appropriate scalar value instead of a full model instance:
Example(1)
Counts the number of user in users table
<?php
namespace App\Http\Controllers;
use App\Employee;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;//include this
class EmployeeController extends Controller
{
public function index()
{
$employee = Employee::where('active', 1)->count();
return view('employee.index', ['employee' => $employee]);
}
}
?>
<?php
namespace App\Http\Controllers;
use App\Employee;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;//include this
class EmployeeController extends Controller
{
public function index()
{
$employee = Employee::where('id', 1)->max('salary');
return view('employee.index', ['employee' => $employee]);
}
}
?>
<?php
namespace App\Http\Controllers;
use App\Employee;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;//include this
class EmployeeController extends Controller
{
public function index()
{
$employee = Employee::where('id', 1)->min('salary');
return view('employee.index', ['employee' => $employee]);
}
}
?>
<?php
namespace App\Http\Controllers;
use App\Employee;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;//include this
class EmployeeController extends Controller
{
public function index()
{
$employee = Employee::where('id', 1)->sum('salary');
return view('employee.index', ['employee' => $employee]);
}
}
?>
<?php
namespace App\Http\Controllers;
use App\Employee;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;//include this
class EmployeeController extends Controller
{
public function index()
{
$employee = Employee::where('id', 1)->avg('salary');
return view('employee.index', ['employee' => $employee]);
}
}
?>