user101
user101

Reputation: 101

How to print the sql count in a view?

I have this

$noOfcomment = DB::select("SELECT COUNT(comment) as cs FROM comments WHERE placeid='$pid->placeid'"); 

But I don't know how to print the result in a view ?

Upvotes: 1

Views: 475

Answers (2)

Basheer Kharoti
Basheer Kharoti

Reputation: 4302

I suggest to use Laravel Eloquent aggregate function instead using the DB facade

$noOfcomments = Comment::where('placeid', your id here)->count();

To pass the data into a view

return view('viewname', compact('noOfcomments'));// and echo $noOfcomments variable in your view

Where as SELECT method returns an array and you are select a specific column then I assume you could access count variable like

$noOfcomment = DB::select("SELECT COUNT(comment) as cs FROM comments WHERE placeid='$pid->placeid'"); 
print_r($noOfcomment[0]->cs);

Upvotes: 0

faressoft
faressoft

Reputation: 19651

The select method will always return an array of results.

print_r($noOfcomment);

To print the count:

echo $noOfcomment[0]->cs;

To print the result in a view you have to pass a variable:

return View::make('viewName', array('count' => $noOfcomment[0]->cs));

Then print the result in your view:

<?php echo $count; ?>

To get more details about the database with Laravel, please check:

http://laravel.com/docs/4.2/database

To get more details about view in Laravel, please check:

http://laravel.com/docs/4.2/responses

Upvotes: 2

Related Questions