在 Laravel 中处理表单中的数据时,我很难在两种不同的方法之间做出选择。这两种方法的解释如下:
1:在验证后使用经过验证的数据进行创建
$validatedData = $request->validate([
'customer_id' => 'required|integer|exists:users,id',
'request_id' => 'required|integer|exists:requests,id',
'addressInfo.city' => 'required|string|max:255',
'addressInfo.district' => 'required|string|max:255',
'addressInfo.neighborhood' => 'required|string|max:255',
'addressInfo.addressDetail' => 'nullable|string|max:500',
'description' => 'required|string|max:500',
'files.*' => 'nullable|file|mimes:jpeg,png,jpg,pdf|max:2048',
]);
$company = getCurrentCompany();
$customer = $company->customers()->findOrFail($validatedData['customer_id']);
$request = $customer->requests()->findOrFail($validatedData['request_id']);
$photos = [];
// File upload processing
foreach ($request->files ?? [] as $index => $file) {
if ($request->hasFile('files.' . $index)) {
$photos[] = [
'index' => $index,
'file' => $request->file('files.' . $index)->store('keyRequests/photos')
];
}
}
// Prepare extra data
$validatedData['photos'] = $photos;
$validatedData['requester_model'] = 'App\Models\Company';
$validatedData['status'] = KeyRequest::getStatuses()[0];
$validatedData['company_id'] = $company->id;
$validatedData['request_address_id'] = $request->address->id;
$validatedData['deed_id'] = $request->deed->id;
// Create key request
$createData = Arr::except($validatedData, ['confirmation', 'files', 'redirectToEdit']);
$keyRequest = $customer->keyRequests()->create($createData);
2:直接使用请求创建
$validatedData = $request->validate([
'customer_id' => 'required|integer|exists:users,id',
'request_id' => 'required|integer|exists:requests,id',
'addressInfo.city' => 'required|string|max:255',
'addressInfo.district' => 'required|string|max:255',
'addressInfo.neighborhood' => 'required|string|max:255',
'addressInfo.addressDetail' => 'nullable|string|max:500',
'description' => 'required|string|max:500',
'files.*' => 'nullable|file|mimes:jpeg,png,jpg,pdf|max:2048',
]);
$company = getCurrentCompany();
$customer = $company->customers()->findOrFail($validatedData['customer_id']);
$request = $customer->requests()->findOrFail($validatedData['request_id']);
$photos = [];
// File upload processing
foreach ($request->files ?? [] as $index => $file) {
if ($request->hasFile('files.' . $index)) {
$photos[] = [
'index' => $index,
'file' => $request->file('files.' . $index)->store('keyRequests/photos')
];
}
}
// Prepare extra data
$request['photos'] = $photos;
$request['requester_model'] = 'App\Models\Company';
$request['status'] = KeyRequest::getStatuses()[0];
$request['company_id'] = $company->id;
$request['request_address_id'] = $request->address->id;
$request['deed_id'] = $request->deed->id;
// Create key request
$keyRequest = $customer->keyRequests()->create($request->except(['confirmation', 'files', 'redirectToEdit']));
哪种方法更安全、更受青睐?
两种方法之间有性能差异吗?
一般来说,每种方法在什么情况下会被推荐?
谢谢您的帮助!
还有第三种选择,它比这两种更好
使用请求表进行验证 为什么? 有以下几个原因
根据你的问题,最好的方法是使用validatedData
为什么?
因为您将确定数据已经过验证,并且未经任何验证就不会通过,
其实没有什么区别