Hello guys!
I've got this problem where I have pretty large form to submit.
This single form holds the data witch belongs to three different tables in my database.
Therefore I made 3 different Models for those tables to make use of Eloquent relationships.
To persist the data I need to use those 3 models all in the same store method in my controller I believe. I know I'm doing something wrong. This is already a very big block of code for a simple controller. I would like to simplify that a bit. Here is what I've got in my controller so far. Have a look.
public function store(Request $request)
{
$validated = $request->validate([
'type_id' => 'required|digits_between:1,3',
'imei_or_serial' => 'required|digits:15',
'vendor' => 'required|alpha|max:20',
'model' => 'required|string|max:20',
'color' => 'required|string|max:20',
'warranty_period' => 'required|string|max:20',
'condition_id' => 'required',
'accessories' => 'required|array',
'warranty_period' => 'required|string|max:20',
'purchase_dt' => 'required',
'source_id' => 'required|digits_between:1,3',
'purchase_price' => 'required|digits_between:2,4',
'stock_price' => 'required|digits_between:2,4',
'second_imei' => 'digits:15',
'added_costs' => 'string|max:50',
'comment' => 'string|max:255'
]);
$device = Device::create([
'type_id' => $validated['type_id'],
'imei_or_serial' => $validated['imei_or_serial'],
'second_imei' => isset($validated['second_imei']) ? $validated['second_imei'] : null,
'vendor' => $validated['producent'],
'model' => $validated['model'],
'color' => $validated['color'],
'accessories' => json_encode($validated['accessories'], JSON_UNESCAPED_UNICODE),
]);
Purchase::create([
'device_id' => $device->id,
'shop_id' => Auth::user()->id,
'source_id' => $validated['source_id'],
'condition_id' => $validated['condition_id'],
'purchase_dt' => Carbon::now(),
'added_costs' => isset($validated['added_costs']) ? $validated['added_costs'] : 0,
'purchase_price' => $validated['purchase_price'],
'warranty_period' => $validated['warranty_period'],
'comment' => isset($validated['comment']) ? $validated['comment'] : null
]);
Depot::create([
'device_id' => $device->id,
'shop_id' => Auth::user()->id,
'stock_price' => $validated['stock_price']
]);
return redirect()->back();
}
I would be more then happy if you could give me some advice on that.