AE1995
AE1995

Reputation: 372

Edit request data before validation

Request data:

    [
        "invoice_data" => [
            ...
            "discount" => null,
        ],
        "product_credit" => [
            ...
            "discount" => null,
        ]
    ];

What I am trying to do

I am trying to create an if statement to check if the

$request -> invoice_data['discount'] == null then set it to 0 ALSO

$request -> product_credit['discount'] == null then set it to 0

Before the validation process because the validation will fail.

What I have tried:

I have found a method in Laravel called prepareForValidation() and it use $this -> merge([...]) which is what I am looking for but problem is that I cannot access the discount in invoice_data and product_credit.

Upvotes: 1

Views: 64

Answers (2)

user10128333
user10128333

Reputation: 156

Cleaner way to set a default value of attributes than editing in request payload:

Model {
   protected $attributes = [
      'inovice_data' => 0,
      'discount' => 0,
      'product_credit' => 0
   ];
}

In this way, if no values are provided, or undefined value or null, Eloquent will set these attributes to defined default values while populating in db.

Upvotes: 1

Jimmix
Jimmix

Reputation: 6506

<?php

$data =
[
        "invoice_data" => [
            "discount" => null,
        ],
        "product_credit" => [
            "discount" => null,
        ]
    ];

$keyWhitelist = [
    'invoice_data',
    'product_credit'
];

foreach ($data as $key => $entry) {

    if(!in_array($key, $keyWhitelist)) {
        continue;
    }

    if(key_exists('discount',$entry)) {
        if ($entry['discount'] === null) {
            $data[$key]['discount'] = 0;
        }
    }
}

var_export($data);

gives result:

array (
  'invoice_data' => 
  array (
    'discount' => 0,
  ),
  'product_credit' => 
  array (
    'discount' => 0,
  ),
)

Upvotes: 0

Related Questions