How to total fields in Lade using Laravel?

Asked

Viewed 2,962 times

0

Dear, I’m making a dashboard, and set up a table on HTML, in a View and I need to tally some columns, and I’d like to do that right at HTML, but how I’m using DB::select I can’t use the command SUM.

  • Is there any other way?
  • Can I add inside the HTML, using some command?
  • Enter your code? please! A View and the Controller responsible!

  • What version of Laravel?

  • You can use variables to sum the values

  • Variables in html itself

2 answers

1


In Laravel the object returned in the query is the Collection. It has a method called sum, that you can use to add up specific fields (only that the sum is based on the results loaded by PHP, and not what is in the database).

$produtos = DB::table('produtos')->select('quantidade', 'preco')->get();

$total_produtos = $produtos->sum('quantidade');

$total_preco = $produtos->sum('preco');

return view('minha_view', compact('total_produtos', 'total_preco');
  • I did the totals and played in variables, but as I have to display the total of different columns according to the module, I ended up making totals of all columns. But I wanted you to have something that you could use directly on . Blade to add up the column. .

0

To solve this problem you can put the return of your query in a variable and pass to the view the total of items of this variable. would look something like:

Controller

$dados = DB::select('sua query'); 
$total = $dados->count();
return view('nome da sua view')

In your view you can get the total value this way:

<div> {{$total}} </div>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.