'Laravel Validator Not Returning Key

I am creating a new API call for our project.

We have a table with different locales. Ex:

ID  Code
1   fr_CA
2   en_CA

However, when we are calling the API to create Invoices, we do not want to send the id but the code.

Here's a sample of the object we are sending:

{
   "locale_code": "fr_CA",
   "billing_first_name": "David",
   "billing_last_name": "Etc"
}

In our controller, we are modifying the locale_code to locale_id using a function with an extension of FormRequest:

   // This function is our method in the controller
public function createInvoice(InvoiceCreateRequest $request)
    {
        $validated = $request->convertLocaleCodeToLocaleId()->validated();
}

// this function is part of ApiRequest which extend FormRequest
// InvoiceCreateRequest extend ApiRequest
// So it goes FormRequest -> ApiRequest -> InvoiceCreateRequest
public function convertLocaleCodeToLocaleId()
    {
        if(!$this->has('locale_code'))
            return $this;

        $localeCode = $this->input('locale_code');

        if(empty($localeCode))
            return $this['locale_id'] = NULL;
        
        $locale = Locale::where(Locale::REFERENCE_COLUMN, $localeCode)->firstOrFail();

        $this['locale_id'] = $locale['locale_id'];

        return $this;
    }

If we do a dump of $this->input('locale_id') inside the function, it return the proper ID (1). However, when it goes through validated();, it doesn't return locale_id even if it's part of the rules:

public function rules()
    {
        return [
            'locale_id' => 'sometimes'
        ];
    }

I also tried the function merge, add, set, etc and nothing work.

Any ideas?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source