Search code examples
laravelsumstrpos

Laravel: Get a list of items and SUM


It is hard to make a question! Well, I have this object from $request:

{
"_method": "POST",
"_token": null,
"cliente": "1",
"cota": "853",
"grupo": "07384",
"idERP": "1",
"novoSegmento": "3",
"nrocpfCnpj": "00635344000177",
"natureza_juridica": "206-2 - Sociedade Empresária Limitada",
"porte": "MICRO EMPRESA",
"originalSegmento": "7",
"example_length": "10",
"cota853": "12975",
"cota209": "12110"
}

I must sum the values from the cota*** and it is quite tricky to do. First I´ve searched for the word 'cota' within this $result using:

if (strpos($request, 'cota') !== false) {
            return 'true';
        }

From now on, I can´t figure out how to continue: 1-) Get how many 'cota'? 2-) How to get each value to make the sum?

Any ideas? Is this the best way? I hope I made myself clear.

Thanks in advance!


Solution

  • If you are passing this using a form, you can better make an array of cotas and then sum them using the powerful collection in laravel, like this:

    // in your blade
    
    <input name="cota[]" value="100" />
    <input name="cota[]" value="200" />
    
    // in the controller
    
    $total = collect($request->get('cota'))->sum();
    

    or iterate over the request values and sum the cota:

    $total = 0;
    foreach ( $request->all() as $key => $value )
    {
        if (strpos($key, 'cota') !== false) {
            $total += $value;
        }
    
        // or regex version to exclude the cota
        if ( preg_match('/cota[0-9]+/', $key) )
        {
            $total += $value;
        }
    
    }
    
    // here you will have the total sum