Changing input values before request validation

Submitted by kamaroly - 8 years ago

Let's say, that your user provide inputs which has arrays like multiple accounts and different crediting and debiting amount, and you need to validate if they are balancing. You will need to extract the array and do some sort of manipulations before proceeding to validation...You can just overload the all() method in your form request class

         /**
     * Modifying input before validation
     * @return array
     */
    public function all()
    {
      /* Grab all inputs which should look like below 
      ***********************************************
         array[
                  "movement_type" => "0"
                  "operation_type" => "0"
                  "amount" => "530000"
                  "charge" => "20"
                  "wording" => "just wording for this transaction"
                  "cheque_number" => "just check number"
                  "bank" => "0"
                  "debit_accounts" =>  [
                    0 => "2"
                    1 => "18"
                  ]
                  "debit_amounts" => [
                    0 => "40000"
                    1 => "13000"
                  ]
                  "credit_accounts" => [
                    0 => "1"
                    2 => "7"
                  ]
                  "credit_amounts" =>  [
                    0 => "20000"
                    2 => "330000"
                  ]
                ]
      */
        // Grab all inputs from the user
        $attributes = parent::all();

        // Modify or Add new array key/values
        // Validating account amount
        $attributes['accounting_amount'] = array_sum($attributes['debit_amounts']);
        $attributes['accounting_amount_confirmation'] = array_sum($attributes['credit_amounts']);
        
        // Validate total amount vs Account amount
        $attributes['total_amount_credit_amount'] = $attributes['amount'];
        $attributes['total_amount_credit_amount_confirmation'] = $attributes['accounting_amount_confirmation'];

        // Format/sanitize data here

        return $attributes;
    }