Php 将已验证的数组对象从插入数据库中排除
我试图仅在验证后才将数组中的对象排除在数据库中。下面是代码示例Php 将已验证的数组对象从插入数据库中排除,php,laravel,api,Php,Laravel,Api,我试图仅在验证后才将数组中的对象排除在数据库中。下面是代码示例 public function store(Request $request) { // $request->merge([ 'added_by' => auth('api')->user()->id, ]); $travel = TravelSummary::create( $this->validateRequest($id = null) );
public function store(Request $request)
{
//
$request->merge([
'added_by' => auth('api')->user()->id,
]);
$travel = TravelSummary::create( $this->validateRequest($id = null) );
event(new TravelRequestCreatedEvent($travel, $action = 'added travel request'));
return (new TravelSummaryResource($travel))
->response()
->setStatusCode(Response::HTTP_CREATED);
}
下面是已验证字段的数组
private function validateRequest($id){
return request()->validate([
'travel_request_no' => $id ? 'required' : 'required|unique:travel_summaries',
'purpose' => 'required',
'total' => 'nullable',
'cash_advance' => 'nullable',
'advance_amount' => 'nullable|lte:total',
'added_by' => 'required'
]);
}
只有在验证后才能排除总数吗?使用
$data = $request->only(['travel_request_no', 'purpose', 'cash_advance', 'advance_amount', 'advance_amount']);
或
验证后,将该数据传递给创建模型。这里有一个例子
$this->validateRequest($id = null);
$data = $request->only(['travel_request_no', 'purpose', 'cash_advance', 'advance_amount', 'advance_amount']);
//or you can use except
//$data = $request->except(['total']);
$travel = TravelSummary::create($data);
您可以在验证后取消设置要排除的数据,如下所示:
// The validator will return the validated data as an array
$data = $this->validateRequest($id = null);
// This will remove the key and value from the array.
unset($data['total']);
$travel = TravelSummary::create($data);
// The validator will return the validated data as an array
$data = $this->validateRequest($id = null);
// This will remove the key and value from the array.
unset($data['total']);
$travel = TravelSummary::create($data);