Laravel中POST请求的Boolean字段无法保存问题求助
Laravel布尔字段无法存入数据库问题
通过POST请求向Laravel控制器提交包含布尔类型字段的数据,除布尔字段外其余数据均可正常保存。模型的$fillable已配置相关布尔字段(如overnight、isResort等),使用create方法创建数据时,dump创建后的模型能看到正确的布尔值,但数据库中并未保存这些值。
模型$fillable配置
protected $fillable = [ 'name', 'code', 'governorate', 'point', 'overnight', 'isResort', 'family', 'youth', 'status', 'description', 'user_id', 'price_currency', 'map', 'checkoutMessage', 'checkoutYoutubeVideo', 'max_person_count', 'more_person_price', 'age_limit', 'productYoutubeVideo', 'resortProductCount', ];
控制器代码
public function store(Request $request) { try{ $data = $request->all(); $data['user_id'] = auth('user-api')->user()->id; $gev_id = Str::before($request->governorate_id, ','); $product = RentProduct::create($data); $product->update([ 'code' => $gev_id.rand((int)0, (int)pow(2, 256)).$product->id, ]); return $this->returnData("product", RentProduct::where('id', $product->id)->with('photos')->get()); }catch(\Throwable $th){ return $this->returnError($th->getCode() , $th->getMessage()); } }
Postman请求截图

可能的解决方案
1. 检查数据库字段类型
确保数据库中overnight、isResort等布尔字段的类型为boolean或tinyint(1)(Laravel会自动映射这两种类型为布尔值)。如果字段类型是varchar或其他非数值类型,布尔值会被转成字符串存入,导致数据库无法正确识别。
2. 手动转换请求中的布尔值
Postman提交的布尔值如果是字符串"true"/"false",Laravel不会自动转换为布尔类型。可以在控制器中手动处理:
// 定义需要转换的布尔字段列表 $booleanFields = ['overnight', 'isResort', 'family', 'youth', 'status']; foreach ($booleanFields as $field) { if (isset($data[$field])) { $data[$field] = filter_var($data[$field], FILTER_VALIDATE_BOOLEAN); } }
3. 配置模型属性转换
在模型中添加$casts属性,强制指定字段的布尔类型,Laravel会自动处理数据转换:
protected $casts = [ 'overnight' => 'boolean', 'isResort' => 'boolean', 'family' => 'boolean', 'youth' => 'boolean', 'status' => 'boolean', ];
4. 添加请求验证规则
通过验证确保布尔字段的输入合法,避免非法值导致存储异常:
$request->validate([ 'overnight' => 'boolean', 'isResort' => 'boolean', 'family' => 'boolean', 'youth' => 'boolean', 'status' => 'boolean', // 其他字段的验证规则... ]);
内容的提问来源于stack exchange,提问作者Mohamed Gamal
相关产品推荐
相关产品推荐

