多个类别和每个类别的Laravel验证规则具有多个子类别

时间:2017-12-26 09:31:27

标签: php laravel

我知道如何验证多个类别,如:

'categories' => 'required|array',
'categories.*' => 'required|exists:categories,id'

但我不知道如何验证每个类别的子类别

@foreach($attributes as $attribute)
    @if(count($attribute['properties']) > 0)
    <div class="form-group">
        <label  class="col-md-4 control-label">{{ $attribute['title']}} <span class="text-danger">*</span></label>
        <div class="col-md-6">
            <select class="form-control {{($attribute['select_many'] == 1) ? 'mt-select2' : ''}}  dynamic attribute_{{$loop->index}}" name="attribute[{{$attribute['id']}}][]"  {{($attribute['select_many'] == 1) ? 'multiple' : ''}}  required style="width: 100%">
                <option value="">Select</option>
                @foreach ($attribute['properties'] as $key => $value)
                    <option value="{{$key}}"  {{( in_array( $key, ( empty($propertiesSelected) ) ? [] : array_unique($propertiesSelected[$attribute['id']]) ) ) ? 'selected' : '' }}>{{$value}}</option>
                @endforeach
            </select>
        </div>
    </div>
    @endif
@endforeach

2 个答案:

答案 0 :(得分:1)

据我了解您的需要,您可以添加额外的 .field_name ,因此您的代码就是:

'categories.*.name' => 'required|exists:categories,id'

如果您需要更多选项,也可以参考Validator Doc,它写得非常好。

答案 1 :(得分:0)

您必须添加custom validation rule,这是一个示例:

AppServiceProvider方法下的boot课程中:

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use Illuminate\Support\Facades\Validator;

class AppServiceProvider extends ServiceProvider
{

    public function boot()
    {

        // Extend laravel validation rules
        Validator::extend('subcategories_exist', function ($attribute, $categories, $parameters, $validator) {

            // $categories represent the incoming categories value from client
            foreach ($categories as $subCategories) {

                foreach ($subCategories as $category_id) {

                    // check category existence in database
                    return App\Category::where('id', $category_id)->count() === 1;

                }

            }

        });
    }

    ...

}

<强>控制器:

'categories' => 'required|array|subcategories_exist',