You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel从数据库读取验证规则存入数组后无法生效

Fixing Your Database-Stored Validation Rules Issue

The problem in your code is that you're building an array of arrays instead of a flat associative array, then wrapping that in another array when passing to the validator. Laravel's Validator::make() expects a flat associative structure where keys are field names and values are validation rule strings—your current setup doesn't match what it needs.

Let's Break Down the Problem

Your current loop creates $Rules like this:

$Rules = [
    ['title' => 'required|string'],
    ['content' => 'required|min:10'],
];

Then passing [$Rules] to the validator makes the final structure even more nested, which the validator can't interpret correctly.

Solution 1: Fix the Loop

Instead of pushing arrays into $Rules, assign each field directly as a key-value pair:

$data = model::where('page','post.create')->get();
$Rules = []; // Initialize empty array
foreach($data as $value){
    $Rules[$value->post_name] = $value->validation; // Assign field and rule directly
}
$validator = Validator::make($request->all(), $Rules); // Pass $Rules directly, no extra array wrapping

This creates the flat associative array the validator expects:

[
    'title' => 'required|string',
    'content' => 'required|min:10',
]

Solution 2: Use pluck() for Cleaner Code

Laravel's collection has a pluck() method that builds this array in one line, no loop needed:

$Rules = model::where('page','post.create')->pluck('validation', 'post_name')->toArray();
$validator = Validator::make($request->all(), $Rules);

pluck('validation', 'post_name') uses post_name as the array key and validation as the corresponding rule value, then toArray() converts the collection to a plain PHP array.

Important Notes

  • Ensure your validation database column stores rules as valid Laravel validation strings (e.g., 'required|email|max:255'—avoid serialized arrays or JSON unless you decode them first).
  • If rules include dynamic parameters (like model IDs), you’ll need to parse and replace those values before passing to the validator.

内容的提问来源于stack exchange,提问作者Saiba Joichiro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 07:05:43