Laravel: How to calculate sum of column values using eloquent? - laravel

I'm trying to use sum() get the sum of column value, but unfortunately it isn't working and I can't figure out where I am wrong.
$total = Invoice::where('status', 'Completed')
->sum('amount');
This returns error Call to a member function first() on string
invoices (Table)
id
code
status
amount
1
000001
Completed
300.00
2
000002
Completed
500.00
3
000003
Pending
100.00
I want to display the sum of invoices' amount in the view.
Blade View
Activity
Count
Total Amount
Invoices
6
900.00

try this:
$total = Invoice::select(
DB::raw(SUM(amount) as total_amount)
)->where('status', 'Completed')->pluck('total_amount');
and foreach the value in the view file like:
#foreach(total as total_value)
<td>{{total_value}}</td>
#endforeach

convert the `amount` attribute into Int before storing into database.for example
$amount = $request->amount;
$invoice = new Invoice();
$invoice->amount = (int)$amount;
--
--
--
$invoice->save();
then you can use the above query for column sum

Related

how to loop through table in laravel calculate sum of a column

How do i calculate the totals of all values of a column amount after fetching it in laravel controller. table collections has only amount and id column and i want to determine the totals.
You can use sum from eloquent:
$amount = Collections::sum('amount');
You can do the following:
$total = 0;
$amounts = Collections::all()->pluck('amount');
foreach($amounts as $amount){
$total += $amount;
}

How to maintain total column in database

I'm new to laravel. I have one income table in the database and I want to maintain the total amount of users but there is a condition if the same user adds new deal_price then all the column will be updated except total and total will be updated like old deal_price+new deal_price.
this my controller
public function storeincome(Request $request){
$date=$request->get('date');
$parse_date=Carbon::parse($date)->format(' d-m-y H:i');
$party_name = $request->Input('party_name');
$deal_price = $request->Input('deal_price');
$mode = $request->Input('mode');
$slug = Str::slug($party_name, '');
$total = $request->Input('deal_price');
$data = array('date'=>$parse_date,'party_name'=>$party_name,'deal_price'=>$deal_price,'mode'=>$mode,'party_slug'=>$slug,'total'=>$total);
Income::insert($data);
return redirect(route('admin.dashboard'))->with('success', trans('message.success.create'));
}
this my table colums
Thanks.
Just update other columns normally and while updating the column 'total', fetch the value of deal_price(old) from your database and store it in a variable ($old_deal_price).
Now, just add the old_deal_price ($old_deal_price) and new_deal_price ($request->deal_price) and update that value in your 'total' field.
$total = ($old_deal_price) + ($request->deal_price);
Goodluck!

get all rows in single query with multiple id

I have a asset_request table with fields id and request_id.
I want to select multiple rows with specific ids.
$ids = $request->ids // 5,6
I want to select only rows with ids of 5 and 6 in request table
$ids = $request->ids;
$asset_request = asset_request::whereIn('id',array($ids))->first(); //gets only 6th row.
I need to get all rows matching the given ids.
To clarify after a chat discussion with the Op:
The Op was passing back a string request, therefore, the Op needed to change the following:
$id = $request->id;
$ids = str_split(str_replace(',', '', $id));
$asset_request = asset_request::whereIn('id', $ids)->get();
First you are calling the first method which will return only the first row matched.
You need to call get method to get all rows matched.
Secondly if you are sending ids as a comma separated string you need to convert it to array using explode.
$ids = $request->ids;
$asset_requst = asset_request::whereIn('id', explode(",", $ids))->get();
DB::table('asset_request')
->whereIn('id', (array) $request->ids)
->get();
or
TableModel::whereIn('id', (array) $request->ids)->get();

Query max Codeigniter

I have a query that result 2 data(s) with the same employee
$this->load->library('datatables');
$this->datatables->select('a.employee_id, a.name, b.employee_position');
->from('employee a')
->join('employee_position b','b.employee_id = .a.employee_id AND `b`.`deleted`=0 AND `c`.`date_start` <= "'.$now_date.'"','inner')
$data = $this->datatables->get_adata();
$aaData = $data->aaData;
I wan't only one data appear which is choosing the max data on date_start column, how to do it?
Add these two lines in your code:
$this->db->order_by('c.date_start', 'DESC');
$this->db->limit(1, 1);

Using whereIn method to return multiple results for the same array value but at different index

$pidArray contains product ID's, some of those product ID's can be the same. I.E: 34 34 56 77 99 34. As is, it appears the whereIn method does not return results for a productId it has already found in $pidArray, even if it has a different index.
$productDataForOrder = Product::whereIn('id', $pidArray)->get(['id','price']);
$totalAmount = $productDataForOrder->sum('price');
$productDataForOrder now contains product data, but only for unique ProductID's in $pidarray. So when sum function is run, the sum is wrong as it does not take into account the price for multiple instances of the same productID.
The following code also does not return objects for every product ID in the array which are the same. So if $pidArray contains three identical product ID's, the query will only return a collection with one object, instead of three.
$query = Product::select();
foreach ($pidArray as $id)
{
$query->orWhere('id', '=', $id);
}
$productDataForOrder = $query->get(['id','price']);
$totalAmount = $productDataForOrder->sum('price');
You're not going to be able to get duplicate data the way that you're trying. SQL is returning the rows that match your where clause. It is not going to return duplicate rows just because your where clause has duplicate ids.
It may help to think of it this way:
select * from products where id in (1, 1)
is the same as
select * from products where (id = 1) or (id = 1)
There is only one record in the table that satisfies the condition, so that is all you're going to get.
You're going to have to do some extra processing in PHP to get your price. You can do something like:
// First, get the prices. Then, loop over the ids and total up the
// prices for each id.
// lists returns a Collection of key => value pairs.
// First parameter (price) is the value.
// Second parameter (id) is the key.
$prices = Product::whereIn('id', $pidArray)->lists('price', 'id');
// I used array_walk, but you could use a plain foreach instead.
// Or, if $pidArray is actually a Collection, you could use
// $pidArray->each(function ...)
$total = 0;
array_walk($pidArray, function($value) use (&$total, $prices) {
$total += $prices->get($value, 0);
});
echo $total;
The whereIn method only limits the results to the values in the given array. From the docs:
The whereIn method verifies that a given column's value is contained within the given array
Id make a query variable and loop through the array adding to the query variable in each pass. Something like this:
$query = Product::select();
foreach ($pidArray as $id)
{
$query->where('id', '=', $id);
}
$query->get(['id','price']);
Here is a code that would work for your use case expanding on #patricus
You first fetch an array of key as id and value as price from the products table
$prices = Product::whereIn('id', $pidArray)->lists('price', 'id');
$totalPrice = collect([$pidArray])->reduce(function($result, $id) use ($prices) {
return $result += $prices[$id];
}, 0);

Resources