Count data from database on laravel

Martin Christopher picture Martin Christopher · Jan 29, 2019 · Viewed 22.1k times · Source

On php i could use this code to get how many item on my goods db

$total = 0;
$sql = "select count(*) as total from goods";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        $total = $row['total'];
    }
}
echo $total;
// example return 5

can i do that on laravel? if i use this code on my controller

function show(Request $request){
    $c = DB::select("SELECT count(*) as total FROM goods");
    if($c > 0 ): a ? b;
}

it would get error message since it would return JSON inside array. Are there any better way to do this? Or how to get that total from $c inside controller

Answer

Jignesh Joisar picture Jignesh Joisar · Jan 29, 2019

used laravel Aggregates methods count method

$count = DB::table('goods')->count();

if($count > 0) {
     //more than one raw
}else {
     //zero raw
}