2 回答

TA貢獻1868條經驗 獲得超4個贊
您最好更改查詢,以便僅獲取要查找的用戶的值。
$amount = DB::table('user_check')->where('user_id', $user)->pluck('amount');
或者如果金額是數組而不是單個值(取決于版本)
$amount = DB::table('user_check')->where('user_id', $user)->value('amount');
或
$user = DB::table('user_check')->where('user_id', $user)->first(); $amount = $user ? $user->amount : 0;

TA貢獻1845條經驗 獲得超8個贊
如果值為“假”、“空”或“0”,則 (int) 將返回 0。我敢打賭,你不希望有這個查詢來搜索ID為0的用戶,以防請求輸入未設置或格式不正確。
讓我們清理該代碼:
$userId = request()->get('user');
$money = (int) request()->get('money');
# (int) here will be 0 if the request('money') is not sent with the request
# so it makes sense to have it here.
$userCheck = DB::table('user_check')->select('amount')
->where('user_id', $userId)
->first();
# ->first(); if you want to return a single row item
# ->get(); if you want to return multiple items, this one will return a collection (array)
# and you need to treat that accordingly using foreach, or any array function
為什么需要?$array = json_decode(json_encode($data), True);
if($userCheck->amount > $money){
return response(['user ok'=> $userCheck,'money'=>$money]);
}else{
return response('user not ok');
}
現在我假設你正在使用(int)來獲取已發送數據的整數值,那里沒有實際需要,并且在驗證的情況下,你需要單獨驗證它,如下所示:
如果它在控制器中
$this->validate($request,[
'user'=>'required|exists:user_check,id',
'money'=>'integer'
]);
如果要在其他地方進行驗證,您可以:
$validator = Validator::make($request->all(), [
'user'=>'required|exists:user_check,id',
'money'=>'integer'
]);
# Check if it fails
if($validator->fails()){
# Validator fails, stop and return the errors instead
return response()->with($validator->getMessageBag());
}
# This will validate the request and make sure that it has 'user'
# And that 'user' exists in the `user_check` table with that ID
# and that 'money' is an integer
如果您愿意驗證,則可以將該代碼放在DB::table()...
我希望這能解決你的問題,讓我知道它是如何進行的。
- 2 回答
- 0 關注
- 131 瀏覽
添加回答
舉報