2017-08-14 193 views
0

我的代碼來驗證數據是這樣的:如何驗證laravel中的json數據?

public function register(Request $request) 
{ 
    //echo '<pre>';print_r($request->all());echo '</pre>';die(); 
    $this->validate($request, [ 
     'email'=>'required', 
     'password'=>'required', 
     'data_cache.dataCache.id'=>'required|numeric' 
     'data_cache.dataCache.quantity'=>'required|numeric' 
    ]); 
} 

echo '<pre>';print_r($request->all());echo '</pre>';die();像這樣的結果:

Array 
(
    [data_cache] => {"dataCache":{"id":112,"quantity":1,"information":"stamford bridge","request_date":"15-08-2017 02:30:00"},"expired":"2017-08-14T16:30:26.272Z"} 
    [email] => [email protected] 
    [password] => 87654321 
) 

的data_cache是​​JSON數據

在視圖葉片,我添加此顯示消息驗證:

@if ($errors->has('data_cache')) 
    <span class="help-block"> 
     <strong>{{ $errors->first('data_cache') }}</strong> 
    </span> 
@endif 

如果代碼執行,也沒有顯示消息驗證

似乎驗證JSON數據仍然是錯誤的

我如何做是正確的?

回答

1

你可以嘗試使用...

$dataCache = json_decode($request->data_cache); 

$request->merge(['id' => $dataCache.dataCache.id, 'quantity' => $dataCache.dataCache.quantity]); 

然後用$ validate方法繼續你。

有一個字段,用於檢查驗證下的數據字段是否是有效的json字符串,但這不是您所需要的。