try
$value = $request->input('responses..answer_id') ? $request->input('responses..answer_id') : 1;
public function store(Request $request, Survey $survey, $questionnaireId)
{
$data = $request->validate([
'responses' => 'required|array',
'responses.*.question_tag' => 'required',
'responses.*.question_id' => 'required',
'responses.*.question_category' => 'required',
'responses.*.answer_id' => 'nullable',
'questionnaire.name' => 'required',
]);
$value = $request->input('responses.*.answer_id', 1);
$responses = array_merge($data['responses'], $value);
$questionnaire = $survey->questionnaires()->create($data['questionnaire']);
$questionnaire->responses()->createMany($responses);
Hey all, I'm trying to give my 'answer_id' a default value of 1 if it is left as null. I did the following code but instead of getting 1 when I didn't answer a question I still got null.
What's the correct way of getting around this?
One common misconception of default values in Laravel is that the second parameter will be returned when the value is null.
Actually the default will be returned when the searched key is not present at all.
If the value was sent blank in the request, then the key responses.*.answer is present and so the returned value will be null and not the default passed as second parameter.
Also as you are using the array notation for getting the key, you are expecting an array to be returned. But the default key wouldn't be set for each of the array's items.
Lastly, as you intend to merge back the default value for an array of values, I guess what you are after is this:
public function store(Request $request, Survey $survey, $questionnaireId)
{
$data = $request->validate([
'responses' => 'required|array',
'responses.*.question_tag' => 'required',
'responses.*.question_id' => 'required',
'responses.*.question_category' => 'required',
'responses.*.answer_id' => 'nullable',
'questionnaire.name' => 'required',
]);
$responses = array_map(function ($record) {
// shorter version:
// $record['answer_id'] ??= 1;
$record['answer_id'] = $record['answer_id'] ?? 1;
return $record;
}, $data['responses']);
$questionnaire = $survey->questionnaires()->create($data['questionnaire']);
$questionnaire->responses()->createMany($responses);
}
As this will set the default value for each record.
The problem with your previous code sample is that even if this code line:
$value = $request->input('responses.*.answer_id');
Returns an array, it will return a index-based array and not an associative array.
So when you call array_merge you would end up with an array with both string and integer keys mixed up.
Hope it helps.
Please or to participate in this conversation.