1

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 ?

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

11 Comments

it says Undefined variable: noOfcomment, I want to print the result in my view
What is the result of print_r(DB::select("SELECT * FROM comments LIMIT 1"));
$noOfcomment = DB::select("SELECT COUNT(comment) as cs FROM comments WHERE placeid='$pid->placeid'"); this line was inside my route and I want to display the count result in my view
here's the result Array ( [0] => stdClass Object ( [id] => 1 [userid] => 1 [placeid] => ChIJ38WHZwf9KysRUhNblaFnglM [comment] => comment1 [created_at] => 0000-00-00 00:00:00 ) ) of print_r(DB::select("SELECT * FROM comments LIMIT 1"));
What about: print_r(DB::select("SELECT COUNT(comment) as cs FROM comments WHERE placeid='$pid->placeid'"));
|
0

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

3 Comments

it gives me correct result but I want to display the result in my view 'cause my sql was in routes
it says Undefined variable: noOfcomment (View:
@user101 change variable users to noOfcomments and then print echo $noOfcomments in your view. See the updated answer.

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.