Laravel从数据库读取验证规则存入数组后无法生效
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
validationdatabase 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

