Home > Net >  How to display a stdClass type object such result of SQL Sum() statement in a Laravel view?
How to display a stdClass type object such result of SQL Sum() statement in a Laravel view?

Time:10-27

In the /routes/web.php route file I have the following code:

Route::get('/db', function () {
  $result = DB::select('SELECT SUM(votes) FROM table WHERE column1 = ? AND column2 = ? AND column3 LIKE ?', ['US', 3, '30%']);

  return view('read', ['result' => $result);

I'd like to know how I could display this result in the view. I though something like

{{ $result->SUM(votes)) }}

would work, but it's not the case. I received the following error message:

Call to a member function SUM() on array (View: /var/www/tse/resources/views/read.blade.php)

In the /resources/views/read.blade.php view file I printed/dumped the variable like the following:

<ul>
  <li> {{ print_r ($result); }} </li>
  <li> {{ var_dump ($result); }} </li>
</ul>

<ul>
  <li> {{ $result->SUM(votes) }} </li>
</ul>

and received information as follow:

Array ( [0] => stdClass Object ( [SUM(votes)] => 86820 ) ) 1
array(1) { [0]=> object(stdClass)#291 (1) { ["SUM(votes)"]=> string(5) "86820" } }

So the query is working well (also direct in MySQL), but I'm unable to display the final plain result 86820 inside the unordered list.

CodePudding user response:

Give a simpler alias column name to work with like below:

$result = DB::select('SELECT SUM(votes) as vote_sum FROM table WHERE column1 = ? AND column2 = ? AND column3 LIKE ?', ['US', 3, '30%']);

Then display in your view blade file like below:

<li> {{ $result[0]->vote_sum }} </li>
  • Related