Expense::create($validated + ['code' => generateCode()]);
Mar 17, 2021
5
Level 5
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"
]);
}
Level 3
1 like
Please or to participate in this conversation.