Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

syntaxerron's avatar

How to add custom value in validated form request

I validate data through form request and then pass the values to my controller. In my controller, I wanted to use the Model::create() way of saving data instead of Model->save() because it is shorter and I don't have to set each of the model properties manually. But I have a field 'code' that needed to be set manually by calling a function generateCode() for that certain record. I don't know how it can be applied using Model::create(). I searched for answers on other sites but I found nothing.

Using Model::create() :

public function store(ExpenseStoreRequest $request) {
	
	$validated = $request->validated();
	Expense::create($validated);

	return response()->json([
		"message" => "Created successfully"
	]);
}

Using Model->save() :

public function store(ExpenseStoreRequest $request) {
	
	$validated = $request->validated();
	$expense = new Expense();
	$expense->code = generateCode();
	$expense->save();

	return response()->json([
		"message" => "Created successfully"
	]);
}
0 likes
5 replies
awsqed's avatar
awsqed
Best Answer
Level 3
Expense::create($validated + ['code' => generateCode()]);
1 like
syntaxerron's avatar

Oh wow, thank you. I didn't know that this was even possible.

awsqed's avatar

Please mark it as solved and best answer if it's helpful. Thank you :D

1 like
MichalOravec's avatar

@erron Another option is when you add this to ExpenseStoreRequest

public function withValidator($validator)
{
    $validator->after(function ($validator) {
        $this->merge(['code' => generateCode()]);
    });
}

Then you controller could look like

public function store(ExpenseStoreRequest $request)
{
    Expense::create($request->validated());

    return response()->json(['message' => 'Created successfully']);
}
1 like
syntaxerron's avatar

wow.. thank you for this another great approach..

Please or to participate in this conversation.