Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count data from database on laravel

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

like image 493
Martin Christopher Avatar asked Oct 18 '25 10:10

Martin Christopher


1 Answers

used laravel Aggregates methods count method

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

if($count > 0) {
     //more than one raw
}else {
     //zero raw
}
like image 117
Jignesh Joisar Avatar answered Oct 20 '25 22:10

Jignesh Joisar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!