4

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

Martin Christopher
  • 389
  • 1
  • 7
  • 21

4 Answers4

12

used laravel Aggregates methods count method

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

if($count > 0) {
     //more than one raw
}else {
     //zero raw
}
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
3

You can use count() function like this:

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

You can also use Laravel Eloquent on Good model like this:

$count = Good::count();
Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
Naseh Badalov
  • 334
  • 1
  • 8
0
$count = DB::table('goods')->count();

Please refer link

Jignesh Joisar
  • 13,720
  • 5
  • 57
  • 57
Mohan
  • 85
  • 5
-2

its much cleaner with eloquent

$c=goods::all()->count();

since the above will pull all collection and count, the more efficient way is

$c=goods::where('value',$val)->get()->count();
Emeka Okafor
  • 427
  • 4
  • 10