phplaravelvalidationrule

Laravel Validation Rule array not working


I tried to put all the validation rules to my database and put it to array why is not working when you put it in array?

$data = model::where('page','post.create')->get();
        foreach($data as $value){
          $Rules[] = array($value->post_name => $value->validation);
        }

$validator = Validator::make($request->all(), [$Rules]);

Solution

  • Please read the Laravel documentation properly: https://laravel.com/docs/5.6/validation

    The mistake is in your 2nd argument in Validator::make, you must pass an array with 'field' => 'validation_rule' pairs. E.g.

    [
        'title' => 'required|unique:posts|max:255',
        'body' => 'required'
    ]
    

    This code $Rules[] = array($value->post_name => $value->validation); will automatically append numeric array like for example like this:

    [
        'title' => 'required|unique:posts|max:255'
    ],
    [
        'body' => 'required'
    ]
    

    And this is not what you want. You may also try to learn debugging my friend. Try to check the value of $Rules by running dd($Rules);. So the correct syntax is this:

    $data = model::where('page','post.create')->get();
    foreach($data as $value){
        $Rules[$value->post_name] = $value->validation;
    }
    
    $validator = Validator::make($request->all(), $Rules);