Saiba Joichiro
Saiba Joichiro

Reputation: 3

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]);

Upvotes: 0

Views: 1049

Answers (2)

aceraven777
aceraven777

Reputation: 4556

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);

Upvotes: 0

Boopathi D
Boopathi D

Reputation: 377

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

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

I think you should give the variable name inside array in line 3 and for using array $Rules you should not give the name inside square bracquet in line 5.

Upvotes: 0

Related Questions