目前我有一組數組。和我可以輕松地將這些數據插入到我的數據庫中,Laravel而無需進行任何驗證這是示例數組代碼: $excel1 = Importer::make('Excel'); $excel1->hasHeader(true); $excel1->load($savePath.$fileName); $excel1->setSheet(2); $collection1 = $excel1->getCollection(); $arr1 = json_decode($collection1,true); foreach ($arr1 as $row1) { $insert_data1[] = array( 'projCode' => $projCode, 'emp_id' => $row1['company_id'], 'type' => 'EMP', 'deleted' => 0, 'by_id' => auth()->user()->id, 'updated_by' => auth()->user()->name, 'created_at' => now(), 'updated_at' => now(), ); } dd($insert_data1);輸出:我正在使用此代碼將這些數據插入到我的表中 DB::table('tbl_emp_proj')->insert($insert_data1);這很好用,但問題是,我正在嘗試驗證我的表中是否emp_id存在users這是我的users桌子from 數組的值emp_id應該檢查它是否已經存在于我的users使用company_id字段 from 中users。我如何驗證它是否$insert_data1是一個數組并且應該檢查它是否存在于數據庫中?更新目前我有這個驗證器,我試圖加起來$Insert_data1但是給了我undefined var for $insert_data1。 $validator = Validator::make( [ 'file' => $request->file, 'extension' => strtolower($request->file->getClientOriginalExtension()), ], [ 'file' => 'required|max:5000', 'extension' => 'required|in:,csv,xlsx,xls', ], $insert_data1, [ '*.emp_id' => "required|exists:users,company_id", ] );
1 回答

LEATH
TA貢獻1936條經驗 獲得超7個贊
你可以使用 LaravelValidator來驗證任何數組,就像它是請求輸入一樣。
use Illuminate\Support\Facades\Validator;
$validator = Validator::make(
$insert_data1,
[
'*.emp_id' => "required|integer|exists:users,company_id",
]
);
編輯:
您可以使用驗證器 API 接收錯誤消息和錯誤項。
$failed = $validator->fails(); //boolean
$errors = $validator->errors();
$validated = $validator->validated();
$invalid = $validator->invalid();
- 1 回答
- 0 關注
- 133 瀏覽
添加回答
舉報
0/150
提交
取消