Add New Column To Existing Table And Show It Into A View Blade (LARAVEL,mysql)

my goal is to display the total of the SUCCESS payments in my project in home blade.

if is it possible to do this without creating new column its ok.

step 1 : i have a table named (payments) , i want to add a new column named (total_amount) ,

i already have the amount column so i need to put the SUM of this column to the new one (total_amount).

NOTE : i need just the success payments , so the SUM query need a condition where status = 'success' enter image description here

step 2 : after getting the total amount , i want to show it into home view blade .

i just want to show the total of payments in < h1 >

please i need step by step and what i should put in the controller and model... ,

i try to get the total without creating a new column but wasn't work so i think that i need to create his column first and get the value of this column, note that its just a one value not array.



You don't need to have a sum column. In general, you should avoid storing aggregates. Do something like this instead:

[Controller] $sum = Payment::where('status', 'success')->sum('amount');

Then when you construct the view, make sure to compact sum with the other variables:

[Controller] return view('yourtemplate', compact( 'all', 'your', 'other', 'vars', 'sum' ));

Then in the view itself, just echo out the sum wherever you want it:

[View] <h1>{{ $sum }}</h1>

EDIT: Thought of another way. If you already have the payments as a collection in that view, you can just use the collection helper:

[View] <h1>{{ $payments->where('status', 'success')->sum('amount') }}</h1>