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

4 Answers 4

12

used laravel Aggregates methods count method

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

if($count > 0) {
     //more than one raw
}else {
     //zero raw
}
Sign up to request clarification or add additional context in comments.

Comments

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();

Comments

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

Please refer link

Comments

-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();

2 Comments

This will fetch all goods and count collection, not good, if there are millions of records.
i know its not a good practice but looking at his code, he is fetching all record

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.